Javascript – execute after all images have loaded

Here is a quick hack for modern browsers:

var imgs = document.images,
    len = imgs.length,
    counter = 0;

[].forEach.call( imgs, function( img ) {
    if(img.complete)
      incrementCounter();
    else
      img.addEventListener( 'load', incrementCounter, false );
} );

function incrementCounter() {
    counter++;
    if ( counter === len ) {
        console.log( 'All images loaded!' );
    }
}

Once all the images are loaded, your console will show “All images loaded!”.

What this code does:

  • Load all the images in a variable from the document
  • Loop through these images
  • Add a listener for the “load” event on each of these images to run the incrementCounter function
  • The incrementCounter will increment the counter
  • If the counter has reached the length of images, that means they’re all loaded

Having this code in a cross-browser way wouldn’t be so hard, it’s just cleaner like this.

Leave a Comment