有麻烦预加载图像的问题 [英] Having troubles preloading images with javascript

查看:87
本文介绍了有麻烦预加载图像的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

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

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)现在该功能只是使用
pictures [i] = new Image()预加载所有150张图像;
pictures [i] .src =path / to / my / images /+ imageName [i] +.jpg;

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?

任何想法?

推荐答案


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

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.

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

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

这篇关于有麻烦预加载图像的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆