I can’t seem to find a definitive answer to this one…
Assume I have a JavaScript reference to an image on the page and I bind a load
event handler to that element. For example, something like this:
HTML
<img id="myImage" src="http://example.com/image.jpg" />
JavaScript
var $myImage = $('#myImage'); $myImage.load(function() { alert('Image loaded!') });
Now, if I do this:
var imageElem = $myImage[0]; imageElem.src = imageElem.src; // Re-assign the image source path
…will the load
event handler fire even if the image has already been loaded from the server? It seems to do in Firefox, but is it safe to rely on this behaviour?
(The reason I ask is I’ve seen this used in a jQuery plugin to check when all images have been loaded. If the image is loaded before the load
event handler is bound, then it won’t fire, unless it’s re-triggered using the method above.)
Advertisement
Answer
Setting img.src should trigger load, with some caveats. According to jQuery’s own documentation regarding the .load event,
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