繁体   English   中英

尽管已加载脚本,但未定义jQuery

[英]jQuery is not defined although the script is loaded

我知道这个话题已经被大量讨论,但是我似乎没有找到解决方案。

我尝试在回调中加载多个库,如下所示:

var loadjQuery = function (){
    console.log('loadjQuery');
    try {
        jQuery();
        loadLocalStorage();
    } catch(e) {
        var jq = document.createElement('script');
        jq.type = 'text/javascript';
        jq.src = '//myurl/assets/js/lib/jquery-2.1.1.js';
        jq.onload = function (){ $.noConflict();};
        document.getElementsByTagName('head')[0].appendChild(jq);
        try {
            jQuery();
            loadLocalStorage();
        } catch (e) {
            jq.src = '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js';
            jq.onload = function (){ $.noConflict();};
            document.getElementsByTagName('head')[0].appendChild(jq);
            loadLocalStorage();
        }

    }   
}
var loadCookie = function (){
    console.log('loadCookie');
    try { 
        jQuery.cookie();
    } catch(e) { 
        var cook = document.createElement('script'); 
        cook.type = 'text/javascript';
        cook.src = '//myurl/assets/js/lib/jquery.cookie.js';
        document.getElementsByTagName('head')[0].appendChild(cook); 
    }
}
var loadLocalStorage = function (){
    console.log('loadLocalStorage');
    try { 
        jQuery.localStorage();
        loadCookie();
    } catch(e) { 
        var ls = document.createElement('script'); 
        ls.type = 'text/javascript';
        ls.src = '//myurl/assets/js/lib/jquery.storage.js';
        document.getElementsByTagName('head')[0].appendChild(ls);
        loadCookie();
    }
}

loadjQuery ();

文件全部加载到网络whit 200响应中。 代码也会被加载。 但是当我尝试使用代码时,我得到:

jQuery is not defined

例如,如果我转到文件jquery.storage.js中的错误,则会在此行收到错误:

}(jQuery, window, document));

我仔细研究了这个问题的所有答案。 将脚本放在页眉和页脚中。 设置defer =“ defer”等'...我想念什么?

好吧,这太愚蠢了。 因为js异步工作,所以尽管所有脚本都以正确的顺序加载,并且我可以在控制台中使用jQuery,并且在文档准备就绪后,库仍未初始化,因为此时尚未加载jQuery。

诀窍是在onload函数中添加回调,如下所示:

var loadjQuery = function (){
    console.log('loadjQuery');
    try {
        jQuery();
        loadLocalStorage();
    } catch(e) {
        var jq = document.createElement('script');
        jq.type = 'text/javascript';
        jq.onload = function (){ 
        $.noConflict();
        loadLocalStorage();
        loadCookie();
        };
        jq.src = '//myurl/assets/js/lib/jquery-2.1.1.js';
        document.getElementsByTagName('head')[0].appendChild(jq);   
    }   

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM