问题
I'm trying to preload about 150 images and I want to be able to be able to do two things...
1) The images are being preloaded using a list of file names. Not every single file name in the list has a file to match up to it.
eg) pic04.jpg may not exist, even if it is in the list.
So when I'm preloading, i would like to be able to figure out whether or not the image exists, if possible.
2) Right now the function is simply preloading all 150 images using pictures[i] = new Image(); pictures[i].src = "path/to/my/images/" + imageName[i] + ".jpg";
The function executes extremely fast, but the images don't seem to have been preloaded. Do I need to do something to make the site wait til the images have loaded before continuing?
Any ideas?
回答1:
The function executes extremely fast, but the images don't seem to have been preloaded.
the images are being loaded asynchronously. The function finishes its execution but the browser continues loading the images in background
So when I'm preloading, i would like to be able to figure out whether or not the image exists, if possible.
yes, it is possible. You can use onerror event handler on the Image object
var img = new Image();
img.onerror=function(){alert('error: '+this.src);}
img.onload=function(){alert('image loaded: '+this.src);}
img.src='path/to/image.jpg';
来源:https://stackoverflow.com/questions/922309/having-troubles-preloading-images-with-javascript