2008-12-02 68 views
2

我正在構建一個包含幾百張圖片的幻燈片,並且希望構建一個漂亮的加載欄,所以我們的想法是使用JavaScript預加載圖像,然後初始化剩餘的用戶界面字。如何使用預加載器和多個圖像顯示加載狀態?

預加載圖像不是問題,但讓瀏覽器在加載時更新狀態。我已經嘗試了一些東西,但瀏覽器只會在完成後重新繪製顯示。

我甚至試過了this question這個腳本,但是我得到了同樣的結果。

這裏就是我這麼遠(imgList是文件名的數組我使用Prototype。)

var imageBuf = [] 
var loadCount = 0 
$('loadStatus').update("0/"+imgList.length) 

function init() { 
    imgList.each(function(element){ 
     imageBuf[element] = new Image() 
     //imageBuf[element].onload = window.setTimeout("count()",0) // gives "not implemented" error in IE 
     imageBuf[element].onload = function(){count()} 
     imageBuf[element].src = "thumbs/"+element 
    }) 
} 

function count() { 
    loadCount++ 
    $('loadStatus').update(loadCount+"/"+imgList.length) 
} 

init() 

回答

3

嘗試使用功能從my answer to this question

function incrementallyProcess(workerCallback, data, chunkSize, timeout, completionCallback) { 
    var itemIndex = 0; 
    (function() { 
    var remainingDataLength = (data.length - itemIndex); 
    var currentChunkSize = (remainingDataLength >= chunkSize) ? chunkSize : remainingDataLength; 
    if(itemIndex < data.length) { 
     while(currentChunkSize--) { 
     workerCallback(data[itemIndex++]); 
     } 
     setTimeout(arguments.callee, timeout); 
    } else if(completionCallback) { 
     completionCallback(); 
    } 
    })(); 
} 


// here we are using the above function to take 
// a short break every time we load an image 
function init() { 
    incrementallyProcess(function(element) { 
    imageBuf[element] = new Image(); 
    imageBuf[element].onload = function(){count()}; 
    imageBuf[element].src = "thumbs/"+element; 
    }, imgList, 1, 250, function() { 
    alert("done loading"); 
    }); 
} 

您可能想要修改塊大小參數以及超時的長度以使其行爲與您希望的相同。我不是100%肯定這會適合你,但它是值得一試...

+0

這是非常光滑的賈森。工作很好。你可能會得到這個答案,但我會把問題留待明天。 – 2008-12-02 16:31:11