方法:
function imagesLoaded(imgAr, callback){
var
// This is a copy of the array of images
imageAr = imgAr.slice(0),
// This holds the javascript Image Objects
images = [],
// This is the number of Images that has loaded
loadedCount = 0;
var imageLoaded = function(){
// An image has finished loading, so increment the number of images loaded by 1
loadedCount++;
if(loadedCount>=imageAr.length){
// If all images have finished loading, run the 'callback' function, to report back that images have all loaded
callback.call();
}
}
// Loop around each image url
for(var i=0;i<imageAr.length;i++){
// For each image, create a new object
images[i] = new Image();
// when the image finishes loading, call the imageLoaded function
images[i].onload = imageLoaded;
// Assign the image the appropriate src attribute
images[i].src = imageAr[i];
}
}
使用する:
var imageAr = ['a.jpg', 'b.jpg', 'c.jpg'];
imagesLoaded(imageAr, function(){
alert('Images loaded!');
});