2011-10-06 72 views
1

我正在一个JavaScript,它按顺序加载其他外部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文件仅在前一个文件加载完成时才启动。

在此先感谢

+1

你可以查看head.js,这是完全的,看看他们是如何实现它。 http://headjs.com/ –

回答

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

而且,考虑使用谷歌或微软CDN的jQuery的,这将节省您的带宽,希望您的访客将已经拥有它的缓存。

+0

是的,但我也希望在third.js启动之前加载second.js –

+0

编辑以获得更好的建议... – Emyr

1

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

0

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

不过,我建议你只是</body>之前加载的jQuery然后使用$.getScript加载其他.js

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"); 
    } 
} 
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])}};