問題描述
我正在將大量圖像加載到動態 DIV 中,并且我正在使用預加載器來獲取圖像.
I am loading a large number of images into a dynamic DIV and I am using a preloader to get the images.
imageObj = new Image();
imageObj.src = imgpath + imgname;
這些事件中的每一個都會創建一個我可以在 Firebug 中查看和監控的 GET.
Each of these events creates a GET that I can see and monitor in Firebug.
如果我知道圖片的名稱和路徑,我可以查看相關的 XMLHttpRequest 以查看 GET 是否完成?
If I know the name and path of an image, can I watch the relevant XMLHttpRequest to see if the GET has completed?
我不想為此過程依賴(或使用).onload 事件.
I do not want to rely on (or use) .onload events for this process.
偽代碼看起來像這樣......
The pseudo would look something like this...
if (imageObj.GET = 'complete')
有人有這方面的經驗嗎?
Has anyone had any experience of this?
編輯 1
感謝 Bart 的幫助(見下文),我已更改圖像預加載器以存儲圖像對象數組...
Thanks to the help from Bart (see below) I have changed my image preloader to store an array of the image objects...
function imagePreLoader(imgname) {
images[imgnum] = new Image();
images[imgnum].src = imgpath + imgname;// load the image
imgnum ++;
}
然后,在我的所有其他函數都運行以構建內容 DIV 之后,我在下面使用了 image.complete 屬性...
And then, after all my other functions have run to build the content DIVs, I used the image.complete attribute in the following...
var interval = setInterval(function () {
imgcount = imgnum - 1; // because the imgnum counter ++ after src is called.
ok = 1;
for (i=0; i<imgcount; i++) {
if (images[i].complete == false){
ok = 0;
}
}
if (ok == 1) {
clearInterval(interval);
showIndexOnLoad();
}
}, 1000);
這會等到所有圖像都完成后,只有當我從間隔函數中得到ok"時才會觸發 showIndexOnLoad()
函數.
This waits until all the images are complete and only triggers the showIndexOnLoad()
function when I get the 'ok' from the interval function.
所有圖像現在都如我所愿,一次全部顯示,無需額外等待 GET 趕上.
All images now appear as I wanted, all at once with no additional waits for the GETs to catch up.
干得好 Bart 讓我了解 image.complete 屬性.p>
Well done Bart for putting me on to the image.complete attribute.
推薦答案
可以觀察圖片的complete
屬性,看看圖片是否加載完畢.
You can watch the complete
property of the image to see if the image is fully loaded or not.
這是一個例子.
http://jsfiddle.net/t3esV/1/
function load (source) {
var img = new Image();
img.src = source;
console.log('Loading ' + source);
var interval = setInterval(function () {
if (img.complete) {
clearInterval(interval);
complete(img);
}
}, 400);
};
function complete(img) {
console.log('Loaded', img.src);
document.body.appendChild(img);
};
注意:當出現問題并且 complete
從未設置為 true
時,此示例無法清除間隔.
Note: This example fails to clear the interval when something goes wrong and complete
is never set to true
.
我寫了一個簡單的 jQuery.preload 插件來利用 圖像.完整的
屬性.
I wrote a simple jQuery.preload plugin to take advantage of the image.complete
property.
這篇關于如何監控圖像源的滿載狀態的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!