2011-10-06 75 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])}};