2016-04-09 69 views
0

我試圖預加載我的js文件而不執行它們。我的代碼是在Chrome中腳本預加載失敗

for(var i=0; i<preload.length; i++){ 
     o = document.createElement('Object'); 
     o.data = preload[i]; 
     o.width = 1; 
     o.height = 1; 
     o.style.visibility = "hidden"; 
     o.type = "text/cache"; 
     o.className = "hidden"; 
     console.log("Creating: ",o); 

     o.onload = function(){ 
      console.info("Trying to load ",this.data," : ",i); 
      itemloaded(this); 
     } 
     // all others require body 
     document.body.appendChild(o); 
     } 

這工作完全在Firefox和IE,但在Chrome只觸發的日誌Creating這表明o是一個匿名函數,而FF和IE被報告爲Object,和鉻似乎永遠觸發onload

+0

在設置URL('data')之前設置「onload」處理函數*可能是個好主意。 – Pointy

+0

@Pointy我也試過,但它沒有區別 – btdev

回答

-1

爲什麼不使用commonjs或amd? 或試試這個。

var script = document.createElement('script'); 
script.src = 'http://path/to/your/script.js'; 
script.onload = function() { 
// do something here 
} 

document.head.appendChild(script); 
+0

它不是一個單一的腳本。我不想執行它們,直到它們全部被加載。加載後,您的方法會自動執行腳本 – btdev