IE quirk with onload event for <img> elements

I rediscovered something yesterday that I know I've come across in the past. Still, it was driving me crazy until I finally did a little web searching and found what I needed. It was one of those "oh right! I've encountered that before" moments.

I was writing a script that dealt with images and I needed to know when an image had finished loading. Simple enough. Using Gimme (or your favorite addEvent(..)) equalizer the code looks something like:

var myImage = document.createElement('img');
myImage.src = 'http://source.to.image/image.jpg';
g(myImage).addEvent('load', function(e) { alert('Image is done loading!'); });

It turns out that my load handler wasn't always firing in IE (in Firefox it worked consistently). The solution though is super simple.

You just need to make sure that you wire up the load handler before setting the image element's .src property. Why? Because if the image is being loaded from cache, IE (and Opera too) will load the image instantly. In fact, it will have finished loading the image before your load event handler is even wired up, which means, it won't fire!

Just change the code to something like this:

var myImage = document.createElement('img');
myImage.addEvent('load', function(e) { alert('Image is done loading!'); });
myImage.src = 'http://source.to.image/image.jpg';

And there you have it.

Nothing earth-shattering and probably common knowledge for a lot of scripters, but a little refresher never hurts.

One Response

  1. Amy Says:

    I'd never done the exact situation of hooking up an onload handler for an img, but I think the general principle holds: if you have event handlers, hook them up before anything that could potentially fire events for them.

Got something to say?

Please note: Constructive criticism is welcome. Rude or vulgar comments however, are not and will be removed during moderation.