Search code examples
javascriptpreloader

JavaScript, set same image source to different images (preload)


Sorry, maybe not correct title.. I have the next question: I want to make preloading with progress bar. And I stuck on one problem.

[CODE 1]:

//Preloader code
var img = [];
img[0] = new Image();
img[0].src = 'test0.jpg';
img[0].onload = function(){
  //some code
}
//.....
img[100] = new Image();
img[100].src = 'test100.jpg';
img[100].onload = function(){
  //some code
}

//.....
//  all images loaded
//.....
/*
for expample  in this part of code I need put my image 'test0.jpg' into html
*/
var temp_img = new Image();
temp_img.src = 'test0.jpg';

The question is : will it download 'test0.jpg' again or just take it from cache?

or better to do like this [CODE 2]:

//Preloader code
var img = [];
img['test0'] = new Image();
img['test0'].src = 'test0.jpg';
img['test0'].onload = function(){
  //some code
}
//.....
img['test100'] = new Image();
img['test100'].src = 'test100.jpg';
img['test100'].onload = function(){
  //some code
}

//.....
//  all images loaded
//.....
/*
for expample in this part of code I need put my image 'test0.jpg' into html
*/
var temp_img = img['test0'];
// draw temp_img

I want to use CODE 1. But will it slow down my app? Or better to use CODE 2? Thanks in advance.


Solution

  • Both methods have benefits and drawbacks.

    The first method is much lighter on image elements and as a general rule, the fewer DOM elements you generate, the better. There is a chance, though, that the browser will not serve the image from the cache depending on how much information is being loaded. Worst case, you will need to fetch from the network again if the browser has removed the image from the cache.

    The second method is much safer and will keep the image held in memory, meaning even if the browser doesn't cache it, it's still available. It's heavier on image elements, though.

    Which solution is better depends on your situation. If you're not loading a large amount of images, I'd say solution 1 is the better choice as it leverages the browser's cache. If you really can't afford to reload images off the network, though, solution 2 is safer.

    TL;DR Solution 1 shouldn't slow down your application, but solution 2 will ensure you don't fetch from the network again.