jQuery event for images loaded

Is it possible to detect when all images are loaded via a jQuery event?

Ideally, there should be a

$(document).idle(function()
{
}

or

$(document).contentLoaded(function()
{
}

But I can't find such a thing.

I thought of attaching an event like this:

$(document).ready(function()
{
    var imageTotal = $('img').length;
    var imageCount = 0;        
    $('img').load(function(){if(++imageCount == imageTotal) doStuff();});
}

But will this break if an image fails to load? It's critically important for the method to be called, and at the right time.


Solution 1:

Per jQuery's documentation, there are a number of caveats for using the load event with images. As noted in another answer, the ahpi.imgload.js plugin is broken, but the linked Paul Irish gist is no longer maintained.

Per Paul Irish, the canonical plugin for detecting image load complete events is now at:

https://github.com/desandro/imagesloaded

Solution 2:

If you want to check for not all images, but a specific one (eg. an image that you replaced dynamically after DOM is already complete) you can use this:

$('#myImage').attr('src', 'image.jpg').on("load", function() {  
  alert('Image Loaded');  
});  

Solution 3:

You can use my plugin waitForImages to handle this...

$(document).waitForImages(function() {
   // Loaded.
});

The advantage of this is you can localise it to one ancestor element and it can optionally detect images referenced in the CSS.

This is just the tip of the iceberg though, check the documentation for more functionality.

Solution 4:

Use of the jQuery $().load() as an IMG event handler isn't guaranteed. If the image loads from the cache, some browsers may not fire off the event. In the case of (older?) versions of Safari, if you changed the SRC property of an IMG element to the same value, the onload event will NOT fire.

It appears that this is recognized in the latest jQuery (1.4.x) - http://api.jquery.com/load-event - to quote:

It is possible that the load event will not be triggered if the image is loaded from the browser cache. To account for this possibility, we can use a special load event that fires immediately if the image is ready. event.special.load is currently available as a plugin.

There is a plug-in now to recognize this case and IE's "complete" property for IMG element load states: http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js