Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

What is the best way to preload multiple images in 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];
}

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT:

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

Check it out: http://www.rootspot.com/stackoverflow/preload.php

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...