I\'m changing the img src once i\'ve loaded a json file, all this works fine. But I want to make sure the image is completely loaded. Which I can do using:
Based on some testing I did about a year ago, I found no reliable way to get a load event when changing the .src
of an image from one value to another. As such, I had to resort to loading a new image and replacing the one I had with the new one when the new image was loaded. That code has been running successfully in several hundred web sites (it's used by a slideshow) for about a year now so I know it works.
If you set the load handler BEFORE you set the .src
property on a new image, you will reliably get the load event. Here's some code I wrote just earlier today for capturing the load event: jQuery: How to check when all images in an array are loaded?.
This code that attaches the event handler BEFORE setting the .src
works for me in the modern browsers I've tried it in (I didn't test older browsers):
$("img").on("load", function() {
// image loaded here
}).attr("src", url);
You can see it work here: http://jsfiddle.net/jfriend00/hmP5M/ and you can test any browsers you want using that jsFiddle. Just click on the image to cause it to load a new image. It cycles through three different images (setting .src each time), loading two of them uniquely every time (never from the cache) and one from the cache in order to test both cases. It outputs a message to the screen whenever the .load handler is called so you can see if it's called.