【问题标题】:Include the jquery file dynamically [duplicate]动态包含jquery文件[重复]
【发布时间】:2014-02-18 12:52:57
【问题描述】:

我想在需要时动态包含 jquery 文件。
但是有一个问题,出现的错误信息$ is not defined

我做了什么:

// include the file dynamically.
var parent, script;
parent = document.getElementsByTagName('head')[0];
script = document.createElement('script');
script.type = "text/javascript";
script.src = "includes/jquery.js";
parent.appendChild(script);

// The usage
$('#box').remove();

【问题讨论】:

  • 试试script.onload = function () { $('#box').remove() }
  • 如果包含带有脚本标签的脚本是否不会出现错误?
  • @Archer:是的,如果包含带有脚本标签的脚本,则不会发生。
  • 可能你可以用这个,check here
  • 我认为@Pilot 已经一针见血了。

标签: javascript jquery


【解决方案1】:

对于 IE,我认为您需要使用 onreadystatechange 回调。例如

script.onload = script.onreadystatechange = function() {
if (!script.readyState || script.readyState == 'loaded' ||
    script.readyState == 'complete') {
  $('#box').remove();
}
};

【讨论】:

    【解决方案2】:

    处理 onload 事件以确保您的脚本在使用前已加载

    script.onload = function () { $('#box').remove() }
    parent.appendChild(script);
    

    【讨论】:

    • 您的答案在现代浏览器上运行良好,但此解决方案至少在 IE 7 上运行良好。
    • @LionKing 你是真的测试还是盲测?..它可以在所有浏览器中工作..
    • 不,不是盲测,我有 IE 6,7 和 firefox 和 chrome。在ffchromeIE9 上工作正常,但IE 6, 7 不起作用。
    【解决方案3】:

    试试这个:

    (function () {
    
    function loadScript(url, callback) {
    
        var script = document.createElement("script")
        script.type = "text/javascript";
    
        if (script.readyState) { //IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else { //Others
            script.onload = function () {
                callback();
            };
        }
    
        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }
    
    loadScript("includes/jquery.js", function () {
    
         //jQuery loaded
         console.log('jquery loaded');
         $('#box').remove();
    
    });
    
    
    })();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 2013-09-04
      • 1970-01-01
      • 2014-08-28
      相关资源
      最近更新 更多