Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

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

I have an array of images (the exact number of images varies), and when they all load I want some code to execute.

I tried this but it doesn't work:

myImgArray.load(function(){
    alert('loaded');
});

I get

33: Uncaught TypeError: Object [object Object],[object Object],[object Object],[object Object] has no method 'load'

I don't think a for loop or something similar would work because the images might, and probably will, load in 'random' order.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...