2013-09-28 140 views
-3

我有一個Web應用程序,我需要頁面加載後加載許多js腳本。我試圖做到這一點在while循環,就像這樣:動態腳本加載

while (....) { 
    var script = document.createElement('script'); 

    // 
    // Here i'm adding script to the html page 
    // 

    script.onload = function(){ 
    // 
    // Do somthing here 
    // 
    } 

} 

但我有一個問題,我有3個 - 在不同的時間爲5個js腳本,但正確加載只有一個腳本,其他腳本或沒有一時間,在循環加載或我不明白什麼是錯的。如何正確加載,包括到html頁許多js腳本?

謝謝。

+2

添加您的解決方案作爲一個答案,並接受它... – Sinkingpoint

+0

如果混淆的重要部分,沒有人可以與您的代碼幫助。 – Pavlo

回答

2

你可以看看at this blog它解釋了不同的JS加載器......目前我使用的是HeadJS(遠離RequireJS),到目前爲止它確實很好。

我甚至有一個Loader.js類,它是我在我的HTML代碼中加載的唯一腳本(除了head.js本身)並且像魅力一樣工作。

見下面的代碼:

head.js("./js/ink/ink-all.js", 
     "./js/jquery/jquery.js", 
     "./js/html5-boilerplate/plugins.js", 
     "./js/i18next/i18next-1.6.3.js", 
     "./js/reclameAqui/ReclameAqui.js", 
     "./js/reclameAqui/controller/IndexController.js", 
     "./js/reclameAqui/controller/NavBarController.js", 
     "./js/reclameAqui/controller/FooterController.js", 
     "./js/reclameAqui/controller/ApplicationController.js", 
     "./js/angular/angular.js", 
     "./js/reclameAqui/utils/i18n/DictionaryLoader.js", 
     function() { 
      var appReclameAqui; 
      console.info("Loading..."); 
      return appReclameAqui = new ReclameAqui(); 
     }); 
0

找到解決方案。我使用的是[] .forEach代替while循環。