Monday, February 26, 2024
 Popular · Latest · Hot · Upcoming
rated 0 times [  129] [ 2]  / answers: 1 / hits: 57085  / 12 Years ago, sun, june 17, 2012, 12:00:00

Having read other people's questions I thought


would answer my question. I have tried this but it executes the code the instant the page loads (not after the images load).

If it makes any difference the images are coming from a CDN and are not relative.

Anyone know a solution? (I'm not using jQuery)

More From » javascript


Here is a quick hack for modern browsers:

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

[] imgs, function( img ) {
img.addEventListener( 'load', incrementCounter, false );
} );

function incrementCounter() {
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.

[#84853] Friday, June 15, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 406
Total Questions: 104
Total Answers: 121

Location: Iceland
Member since Tue, Jan 25, 2022
2 Years ago