Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load images one after another in JavaScript

My problem is, I have multiple images and want to load like preloader, but the problem is that I want to start load of the second image after completing the first one. In my current code I store all images in one array and using a loop load all images (give the source of all images of the array to an image object), and then all images start loading.

like image 620
ketan Avatar asked Feb 23 '12 11:02

ketan


1 Answers

You want to have a look at the load event.

function loadImagesInSequence(images) {
  if (!images.length) {
    return;
  }

  var img = new Image(),
      url = images.shift();

  img.onload = function(){ loadImagesInSequence(images) };
  img.src = url;
}

loadImagesInSequence(['a.png', 'b.png', 'c.png']);

whenever an image is loaded, the load event is fired. When that happens, we execute the loadImagesInSequence() again. We won't load the same image twice, as Array.shift() removed from the array we simply passed through.

like image 170
rodneyrehm Avatar answered Oct 04 '22 20:10

rodneyrehm