2012-12-27 46 views
0

我遇到了腳本問題。預加載圖片不起作用

我想加載數組中的所有圖像,然後檢查它們是否全部加載,然後再繼續。但它不起作用我也沒有得到任何錯誤,所以我不知道什麼是錯的。

這是我有:

window.requestAnimFrame = (function(){ 
    return window.requestAnimationFrame  || 
      window.webkitRequestAnimationFrame || 
      window.mozRequestAnimationFrame || 
      window.oRequestAnimationFrame  || 
      window.msRequestAnimationFrame  || 
      function(callback, element){ 
      window.setTimeout(callback, 200/100); 
      }; 
})(); 

function img_loader(){ 

for(var i in Images){ 
     Images[i]['img_src'].onload = function() { 
      countImages ++; 
     } 
    } 
} 

function img_load_checker(){ 

    if(countImages == Images.length){ 
     return true; 
    } else { 
     requestAnimFrame(img_load_checker); // keep checking 
    } 
} 


window.countImages = 0; 
img_loader(); 
    if(img_load_checker()){ 
      //this never gets executed - reason is unknown 
    //continue with rest of the script 
    } 

這是結構console.log(Images);

[1: Object, 2: Object] 
1: Object 
img_src: <img> 
2: Object 
img_src: <img> 

任何一個能看到錯誤?

+1

當你說 「它不工作」 你是什麼意思明確? –

+0

你試過調試你的代碼嗎?主持人說了什麼? JSLint說什麼? – elclanrs

+0

'//繼續使用腳本的其餘部分'腳本的這部分內容不會執行。 – Sir

回答

1

您的if語句是永遠不會像那樣工作。

那功能調用不會神奇地坐在那裏等待異步調用返回。

if(img_load_checker()){ 
     //this never gets executed - reason is unknown 
//continue with rest of the script 
} 

使用回電!

for(var i in Images){ 
     Images[i]['img_src'].onload = function() { 
      countImages ++; 
      if (countImages == Images.length) { 
       callSomeMethod(); <-- Call back 
      } 
     } 
    } 
} 

function img_load_checker(){ 

    if(countImages == Images.length){ 
     callNextStep(); 
    } else { 
     requestAnimFrame(img_load_checker); // keep checking 
    } 
} 
img_load_checker(); 
+0

這是否意味着我不能只是'返回true'? – Sir

+0

是的,功能是異步射擊。到時候它會返回任何東西,如果陳述在很久以前完成了。 – epascarello

+0

啊,我看到 - 奇怪的是,雖然負載從未發生。我在加載函數中加入了一個警報測試 - 想知道當它存儲爲對象時它是否不起作用。 – Sir

0

你並不需要一個計時器:

Images[i]['img_src'].onload = function() { 
    if(countImages++ >= Images.length) 
    { 
     loadingHasFinishedNowDoWhateverYouWant(); 
    } 

}