Tuesday, March 15, 2011

Is there a way to determine when 4 images have been loaded using JS?

I have 4 images on a page. I want to trigger a JS event once all 4 images are loaded. I of course can't be sure which order the images will be loaded in, so I can't trigger the event on the last image. One thought was to have a counter, but I can't think of the best way to check when that counter is equal to 4 as I don't like the idea of a setTimeout() checking every 200ms.

Any other ideas?

I'm using jQuery on the site, so I'm thinking that might be some help.

This is the image HTML code:

<img src="/images/hp_image-1.jpg" width="553" height="180" id="featureImg1" />
<img src="/images/hp_image-2.jpg" width="553" height="180" id="featureImg2" />
<img src="/images/hp_image-3.jpg" width="553" height="180" id="featureImg3" />
<img src="/images/hp_image-4.jpg" width="553" height="180" id="featureImg4" />
From stackoverflow
  • count=0;
    $("img").load(function() {
        count++;
        if(count==4) { //All images have loaded
            //Do something!
        }
    });
    
  • As regards Salty's example, it's best to use a closure as to not clubber space with global variables, like such:

    $("img").load(function() {    
        var count = 0;
        var noImages = $("img").size();
        return function () {
            count++; 
            if(count === noImages) { 
                //All images have loaded    
            }
        };
    }());
    

    [Edit]

    Changed the hardcoded value of 4 (count === 4) to the jQuery size function, as to allow more flexibility in the function. (thanks to jeroen's comment)

    Ben Blank : Unless these are the only four images on your page, however, you'll want to assign them a class or otherwise have some way to select just those four from your document. (e.g. `$("img.dynloaded").load(…)`)
    Andreas Grech : Yes exactly, because the $("img") selector is selecting every tag on the page
    jeroen : Thanks, just what I needed, in combination with: var noImages = $("img").size(); instead of 4 to make it more flexible...
    Andreas Grech : jeroen, thanks for the comment; I updated the function now ;-)

0 comments:

Post a Comment