Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...