The strange case of the missing load event

So, a while ago I was fiddling with some JavaScript and wanted a load event on an image. From time to time, the event failed to fire on IE8 and I had no clue why. It looked a bit like this:

jQuery('<img alt="" />', {'src': 'http://...'})
    .load(function(evt) {
        // Handle the event here
    })
    .appendTo('body');

This would work every time in Chrome and Firefox, but for some odd reason it failed in IE8 unless i did a forced reload or manually wiped the cache. As it turns out, IE8 can be insanely fast when it comes to loading images from its cache, so when the Javascript engine gets around to attaching an observer to the load event, the image is already there and the event will never fire. Hmm. Who would have thought an IE-related issue was actually caused by speed.

Looking at the code snippet again, I realized that it was actually highly fragile, and somewhere in the distance I would hear one of my numerous programming teachers scream something while pulling their remaining hair out. One should of course never set the src attribute on an image element until any load-events have been set up. With that in mind, this is the right way to go:

jQuery('<img>')
    .load(function(evt) {
        // Handle the event here
    })
    .attr('src', 'http://...')
    .appendTo('body');

I’m not making that mistake again.

Posted Tuesday, October 2nd, 2012 under Uncategorized.

Tags: ,

Leave a Reply

You must be logged in to post a comment.