这是一个通用的(适用于任意数量的图像)
function preload( images, callback){
var imageElements = [],
counter = images.length,
lfunc = function(){if (--counter === 0 && callback) callback(imageElements);};
// first create the images and apply the onload method
for (var i = 0, len = images.length; i < len; i++){
var img = new Image();
imageElements.push( img );
img.onload = lfunc;
img.src = images[i];
}
}
function codeOncePreloadCompletes(preloadedImages){
// Do whatever you want here
// images are preloaded
// you have access to the preloaded image if you need them
// with the preloadedImages argument
}
// USAGE
preload( ['b.png', 'c.png'], codeOncePreloadCompletes);
// OR
preload( ['b.png', 'c.png'], function(preloadImages){
// write directly here what to do after preload
});