在JavaScript中预加载多个图像的最佳方法是什么? [英] What is the best way to preload multiple images in JavaScript?

查看:78
本文介绍了在JavaScript中预加载多个图像的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个图像文件名数组,

If I have an array of image filenames,

var preload = ["a.gif", "b.gif", "c.gif"];

我想在循环中预加载它们,是否每次都需要创建一个图像对象?下面列出的所有方法都有效吗?一个更好吗?

and I want to preload them in a loop, is it necessary to create an image object each time? Will all the methods listed below work? Is one better?

A。

var image = new Image();
for (i = 0; i < preload.length; i++) {
    image.src = preload[i];
}

B。

var image;
for (i = 0; i < preload.length; i++) {
    image = new Image();
    image.src = preload[i];
}

C。

var images = [];
for (i = 0; i < preload.length; i++) {
    images[i] = new Image();
    images[i].src = preload[i];
}

谢谢!

推荐答案

编辑

实际上,我只是将它进行测试,方法A没有按预期工作:

Actually, I just put it to the test, and Method A does not work as intended:

检查出来: http://www.rootspot.com/stackoverflow/preload.php

如果在页面加载完成后点击第二张图片,它应该是因为它是预加载的,所以它是即时出现的,但第一个没有,因为它在更改源之前没有时间加载。有趣。通过这个新的开发,我将继续使用方法C。

If you click on the 2nd image when the page is finished loading, it should appear instantaneously because it was preloaded, but the first one doesn't because it didn't have time to load before the source was changed. Interesting. With this new development, I'd just go ahead and use Method C.

这篇关于在JavaScript中预加载多个图像的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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