使用 JavaScript 预加载图像时遇到问题

发布于 2024-07-21 20:08:48 字数 380 浏览 5 评论 0原文

我正在尝试预加载大约 150 个图像,并且我希望能够做两件事...

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

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

因此,当我预加载时,如果可能的话,我希望能够弄清楚图像是否存在。

2) 现在该函数只是使用以下命令预加载所有 150 张图像 图片[i] = new Image(); 图片[i].src = "path/to/my/images/" + imageName[i] + ".jpg";

该函数执行速度非常快,但图像似乎没有预加载。 我是否需要做一些事情让网站等到图像加载后再继续?

有任何想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

走过海棠暮 2024-07-28 20:08:48

该函数执行速度非常快,但图像似乎没有预加载。

图像正在异步加载。 该函数完成执行,但浏览器继续在后台加载图像

因此,当我预加载时,如果可能的话,我希望能够确定图像是否存在。

对的,这是可能的。 您可以在 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';

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';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文