Having troubles preloading images with javascript

狂风中的少年 提交于 2019-12-13 03:39:21

问题


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

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