JQuery event for images loaded

domjquery

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.

Best Answer

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