What is the best way to preload multiple images in JavaScript?

If I have an array of image file names,

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

and I want to preload them in a loop, do I need to create an image object every time? Will all of the following methods work? Better?

but.

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

AT.

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

FROM.

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

Thank!

+29
javascript
Apr 17 '09 at 16:58
source share
4 answers

EDIT

Actually, I just put it on a test, and Method A does not work as expected:

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

If you click on the second image when the page is finished loading, it should appear instantly because it was preloaded, but the first does not work because it did not have time to load before the source was changed. Interesting. With this new development, I would just start using method C.

+10
Apr 17 '09 at 17:02
source share

The following code seems to work for me. Its based on [A]

JQuery

 var gallery= ['img/1.png','img/2.png','img/3.png','img/4.png','img/5.png']; var preload_image_object=new Image(); 

//Decision:

 $.each(gallery,function(i,c){preload_image_object.src=c.logo}) 

OR

 $.each(['img/1.png','img/2.png','img/3.png','img/4.png','img/5.png'],function(i,c){preload_image_object.src=c}) 
+3
Nov 09 '10 at 6:27
source share

I always used the following code, which, as I have seen, is used by many other sites, so I would like to make the assumption that this method is most efficient and akin to your c method

 function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0) { d.MM_p[j]=new Image; d.MM_p[j++].src=a[i]; } } } 

I would recommend profiling them with something like firebug

+2
Apr 17 '09 at 17:17
source share

If I remember correctly, I am having problems with Solution A , which was not preloaded in the browser. Although I'm not 100% sure.

Since you are all coding, why not test them, you can even scan them to see which is faster.

+1
Apr 17 '09 at 17:05
source share



All Articles