Oliver Nassar

IE7 and IE8 image onload events

June 01, 2011

I've got some pretty straight-forward, simple code which sets the src of an image object. It works great among normal browsers (eg. Chrome, FF, Safari, IE9) but Internet Explorer 7 and 8 give me a hard time.

Specifically, the onload event doesn't fire. At all. Here's the work around I found:

var preload = (new Image()),
    path = 'http://server.com/bla.jpg';
preload.src = path + '?' + Math.random();
preload.onload = function() {
    alert('w00t');
};

I don't know the logic behind it. If I were to guess, I'd say that after the first time, it gets loaded into IE's memory and therefore gets loaded from there rather than the path specified, bypassing the load event (since it wasn't technically loaded?). I dunno. Either way, above definitely solves my issues.

Without the above code and randomization, callbacks would fire after a cache-clear, but not before or after more-than-one load. Bah.