I’ve written a jQuery plugin that will execute a function before and after an image loads. Essentially this is so we can show a loading animation when displaying large images.
if (typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
return; // 1
}
// 2
if (!this.complete) {
options.preload(this); //3
$(this).load(function () {
options.loaded(this); //4
});
}
- Check for images that have failed to load (e.g.404).
- Check if the image has loaded
this.complete - If not, call the preload function (starts the loading animation)
- Add the callback for the image
loadevent (stops the loading animation)
This works fine in Chrome and Firefox. However, in IE (9) I’m finding that sometimes the preload function fires, but not the loaded function.
I suspect that this could be a possible race condition.
What’s the best way of handling this? Should I just check this.complete again after calling the preload function?
Thanks
Ben
It depends on when the
loadeven handler is attached. If the image is already loaded before attaching the load event handler then the load event is not going to be fired. If you want to avoid such conditions then set thesrcof the image after attachingloadevent handler.