【问题标题】:jQuery dynamically included is not working动态包含的 jQuery 不起作用
【发布时间】:2014-08-27 21:31:15
【问题描述】:

我正在尝试将 jQuery 动态包含到 <head> 中。这是我的代码:

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded 
    var script = document.createElement('script');
    script.src = 'resources/js/jquery.js';
    script.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(script);
    alert(typeof jQuery);
} 

效果很好,我在<head> 中看到了<script> 标签; jquery.js 文件也正确且错误更少。即便如此,我为alert(tyeof jQuery) 得到的只是undefined。为什么?

【问题讨论】:

  • 因为加载库比到达脚本的下一行需要更长的时间?
  • 我怎样才能让它执行呢?我可以为

标签: jquery


【解决方案1】:

尝试添加 jQuery 并在加载后分配回调。

在此处查看带有和不带有回调的示例:http://www.sitepoint.com/dynamically-load-jquery-library-javascript/

(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("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {

         //jQuery loaded
         console.log('jquery loaded');

    });


})();

【讨论】:

    【解决方案2】:

    你需要添加监听器

     script.onload = myCallback;
    

    然后才触发jQuery函数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多