How to call function after document ready AND image load?

HappyDeveloper picture HappyDeveloper · Sep 12, 2011 · Viewed 10.8k times · Source

I was using something like this:

$(document).ready(function() {
  $('#my-img').load(function() {
    // do something
  });
});

But sometimes it fails to execute the second callback (without throwing any errors, so there's nothing to do there), and I'm thinking that maybe the image is being loaded before the document is ready.

If I don't use the $(document).ready() part, it works fine, so I think I'm gonna leave it that way for now. But someone told me that it was a good practice to always do this kind of thing as a callback on document ready, because the document might not be ready. Is that right?

Any thoughts?

Answer

Tchami picture Tchami · Sep 12, 2011

Taken from the documentation on load()

Caveats of the load event when used with images

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

It doesn't work consistently nor reliably cross-browser

It doesn't fire correctly in WebKit if the image src is set to the same src as before

It doesn't correctly bubble up the DOM tree

****Can cease to fire for images that already live in the browser's cache****

Especially the latter is a common problem.

You might try the imagesLoaded plugin, but I've had better luck with the following approach:

var element = $('#my-img');
$("<img/>").load(function () { //create in memory image, and bind the load event
    //do something
    //var imageHeight = this.height;
}).attr("src", element.attr("src"));
//set the src of the in memory copy after binding the load event, to avoid WebKit issues

It's dirty, but if you really need to perform some action after the image has loaded this has been the only reliable approach I've been able to get to work.