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.

4 Responses

  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.

  2. Ben Says:

    You're a lifesaver, I was wondering why IE wasn't firing my onload events.

  3. Matthieu R Says:

    Hi !
    Thanks for the tips, it help me a lot !
    I have the same issue with IE, i had to load images dynamicly in a thumbnail and check for the size to choose a big enough one. The size check have to be done after image loading. But despite of your solution, the images seems to being loaded from cache, onload is triggered before real loading, so most of my pics are shown by javascript with both width and height at a value of zero. I was near to become crazy when i found a good solution, i have to add a timestamp after the image URL, with a hash. IE never reconize the URL and load the image properly :)
    (sorry for my bad english)

  4. 一部の詳細についてimageをしなければならない | テクニカルブログ Says:

    [...] imgの. srcの设定でなくてはならないonload事件を設定し、ダウンロードした写真をしなければならないが、キャッシュメモリのうち、ブラウザーはまだ執行で相手に写真をダウンロードして语句をすれば、onload事件が激しくなる可能性が無視されていました。详细… [...]

Got something to say?

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