Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 628
Emmett Avatar asked Apr 17 '09 16:04

Emmett


People also ask

How do you optimize and preload images?

To preload responsive images, new attributes were recently added to the <link> element: imagesrcset and imagesizes . They are used with <link rel="preload"> and match the srcset and sizes syntax used in <img> element. This kicks off a request using the same resource selection logic that srcset and sizes will apply.

Should you preload JS?

Preloading JavaScript files # Because browsers don't execute preloaded files, preloading is useful to separate fetching from execution which can improve metrics such as Time to Interactive. Preloading works best if you split your JavaScript bundles and only preload critical chunks.


2 Answers

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.

like image 61
Paolo Bergantino Avatar answered Oct 11 '22 09:10

Paolo Bergantino


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(); 

//Solution:

$.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}) 
like image 27
Kent Avatar answered Oct 11 '22 10:10

Kent