有麻烦预加载图像的问题

时间:2021-05-01 20:34:52

I'm trying to preload about 150 images and I want to be able to be able to do two things...

我正在尝试预装大约150张图片,我希望能够做两件事......

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.

1)使用文件名列表预加载图像。并非列表中的每个文件名都有一个与之匹配的文件。

eg) pic04.jpg may not exist, even if it is in the list.

例如)pic04.jpg可能不存在,即使它在列表中。

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";

2)现在该功能只是使用图片预加载所有150个图像[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 个解决方案

#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

对的,这是可能的。您可以在Image对象上使用onerror事件处理程序

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';

#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

对的,这是可能的。您可以在Image对象上使用onerror事件处理程序

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';