如何监控图像源的满载状态
我正在将大量图像加载到动态 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.
相关文章