jQuery: How to check when all images in an array are loaded?

大憨熊 提交于 2019-11-27 15:54:07

The only way I know of to do it is to attach a load handler for each image and keep a count of how many have been loaded. When you reach your total, then they've all been loaded.

Here's code that does that:

var urls = [
    "http://photos.smugmug.com/photos/344291068_HdnTo-Ti.jpg",
    "http://photos.smugmug.com/photos/344292111_SvSfK-Ti.jpg",
    "http://photos.smugmug.com/photos/344291168_nErcq-Ti.jpg"
];

var imgs = [];
var cnt = 0;

for (var i = 0; i < urls.length; i++) {
    var img = new Image();
    img.onload = function() {
        ++cnt;
        if (cnt >= urls.length) {
            // all images loaded here
        } else {
            // still more images to load
        }
    };
    img.src = urls[i];
    imgs.push(img);
}

You can see it in action here: http://jsfiddle.net/jfriend00/7KF7V/

For this to work, the onload handler function has to be assigned before the .src property is set because if the image is in the browser cache, onload may fire immediately before .onload is assigned, thus missing the event.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!