Controlling image load order in HTML

Use Javascript, and populate the image src properties later. The # tells the browser to link to a URL on the page, so no request will be sent to the server. (If the src property was empty, a request is still made to the server – not great.)

Assemble an array of image addresses, and recurse through it, loading your images and calling a recursive function when the onload or onerror method for each image returns a value.


<img src="#" id='img0' alt="[]" />
<img src="#" id='img1' alt="[]" />
<img src="#" id='img2' alt="[]" />


var imgAddresses = ['img1.png','img2.jpg','img3.gif'];

function loadImage(counter) {
  // Break out if no more images
  if (counter==imgAddresses.length) { return; }

  // Grab an image obj
  var I = document.getElementById("img"+counter);

  // Monitor load or error events, moving on to next image in either case
  I.onload = I.onerror = function() { loadImage(counter+1); }

  //Change source (then wait for event)
  I.src = imgAddresses[counter];


You could even play around with a document.getElementsByTagName("IMG").

By the way, if you need a loading image, this is a good place to start.


To avoid multiple requests to the server, you could use almost the same method, only don’t insert image elements until you’re ready to load them. Have a <span> container waiting for each image. Then, loop through, get the span object, and dynamically insert the image tag:

var img = document.createElement("IMG");
img.src = ...

Then the image request is made only once, when the element is created.

Leave a Comment