按顺序加载外部Javascript

时间:2011-10-06 18:31:52

标签: javascript jquery

我正在开发一个javascript,它按顺序加载其他外部JavaScript的列表。

到目前为止我的代码:

function loadJavascript(url){
    var js = document.createElement("script");

    js.setAttribute("type", "text/javascript");
    js.setAttribute("src", url);

    if(typeof js!="undefined"){
        document.getElementsByTagName("head")[0].appendChild(js)
    }
}

loadJavascript("Jquery.js");
loadJavascript("second.js");
loadJavascript("third.js");

我遇到的问题是,有时其他js文件在Jquery文件完成加载之前加载。这给了我一些错误。

是否有可能使下一个JS文件仅在上一个文件加载完成时启动。

提前致谢

5 个答案:

答案 0 :(得分:1)

当然有,但是有整个库围绕着这样做。停止重新发明轮子并使用已经有效的东西。试用yepnope.js或者如果您使用的是Modernizr,它已经可以Modernizr.load

答案 1 :(得分:0)

loadJavascript("Jquery.js");
$(function(){
    $.getScript('second.js', function(data, textStatus){
        $.getScript('third.js', function(data, textStatus){
            console.log("loaded");
        });
    });
}

另外,考虑使用Google或Microsoft CDN作为jQuery,它会为您节省带宽,并希望您的访问者已经将其缓存。

答案 2 :(得分:0)

实际上,没有必要在js函数中加载jquery。但是如果你坚持,你可以callback确保在jquery之后加载其他js。

不过,我建议您在</body>之前加载jquery,然后使用$.getScript加载其他.js

答案 3 :(得分:0)

你可以检查是否加载了jQuery,而不是最好的方法,但如果你真的要等到加载jQuery之后再加载其他脚本,这就是我要做的,通过检查对于$:

loadJavascript("Jquery.js");    

T=0;
CheckIfLoaded();

function CheckIfLoaded() {
    if (typeof $ == 'undefined') {
      if (T <= 3000) {
          alert("jQuery not loaded within 3 sec");
      } else {
          T=T+200;
          setTimeout(CheckIfLoaded, 200);
    } else {
       loadJavascript("second.js");
       loadJavascript("third.js");
    }
}

答案 4 :(得分:0)

在技术方面:浏览器有一个有趣的方式来决定我执行/ eval动态加载JS的顺序,所以在遭受同样的痛苦并检查了很多帖子,库,插件等之后我想出了这个解决方案,自包含,小,不需要jquery,IE友好等等。代码被广泛评论:

lazyLoader = {
    load: function (scripts) {
        // The queue for the scripts to be loaded
        lazyLoader.queue = scripts;
        lazyLoader.pendingScripts = [];
        // There will always be a script in the document, at least this very same script... 
        // ...this script  will be used to identify available properties, thus assess correct way to proceed
        var firstScript = document.scripts[0];
        // We will loop thru the scripts on the queue
        for (i = 0; i < lazyLoader.queue.length; ++i) {
            // Evaluates if the async property is used by the browser
            if ('async' in firstScript ) {
                // Since src has to be defined after onreadystate change for IE, we organize all "element" steps together... 
                var element = document.createElement("script");
                element.type = "text/javascript"
                //... two more line of code than necessary but we add order and clarity
                // Define async as false, thus the scripts order will be respected
                element.async = false;
                element.src = lazyLoader.queue[i];
                document.head.appendChild(element);
            }
            // Somebody who hates developers invented IE, so we deal with it as follows:
            // ... In IE<11 script objects (and other objects) have a property called readyState...
            // ... check the script object has said property (readyState) ... 
            // ... if true, Bingo! We have and IE! 
            else if (firstScript.readyState) {
                // How it works: IE will load the script even if not injected to the DOM...
                // ... we create an event listener, we then inject the scripts in sequential order
                // Create an script element
                var element = document.createElement("script");
                element.type = "text/javascript"
                // Add the scripts from the queue to the pending list in order
                lazyLoader.pendingScripts.push(element)
                // Set an event listener for the script element 
                element.onreadystatechange = function() {
                    var pending;
                    // When the next script on the pending list has loaded proceed
                    if (lazyLoader.pendingScripts[0].readyState == "loaded" || lazyLoader.pendingScripts[0].readyState == "complete" ) {
                            // Remove the script we just loaded from the pending list
                            pending = lazyLoader.pendingScripts.shift()
                            // Clear the listener
                            element.onreadystatechange = null;
                            // Inject the script to the DOM, we don't use appendChild as it might break on IE
                            firstScript.parentNode.insertBefore(pending, firstScript);
                    }
                }
                // Once we have set the listener we set the script object's src
                element.src = lazyLoader.queue[i];
            }
        }
    }
}

当然你也可以使用缩小版:

smallLoader={load:function(d){smallLoader.b=d;smallLoader.a=[];var b=document.scripts[0];for(i=0;i<smallLoader.b.length;++i)if("async"in b){var a=document.createElement("script");a.type="text/javascript";a.async=!1;a.src=smallLoader.b[i];document.head.appendChild(a)}else b.readyState&&(a=document.createElement("script"),a.type="text/javascript",smallLoader.a.push(a),a.onreadystatechange=function(){var c;if("loaded"==smallLoader.a[0].readyState||"complete"==smallLoader.a[0].readyState)c=smallLoader.a.shift(),
a.onreadystatechange=null,b.parentNode.insertBefore(c,b)},a.src=smallLoader.b[i])}};