tags:

views:

3253

answers:

3

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.

+2  A: 

Thanks to Moff, above. The suggestion to use $(window).load(); was a great one. I am now using this event to handle all my jQuery.

I will leave this open for a while to see if someone has a more direct approach.

EDIT: Closing - timeout

Antony Carthy
+11  A: 

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

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

+2  A: 

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