How to Fix the IE9 Image Onload Bug

IE9 has an annoying bug that prevents the onload event from firing for cached images. Here's how to fix that in one line of code, without any of the usual drawbacks.

In case you are unaware: In JavaScript, there is a simple way to react to images being loaded, called the onload event. You frequently need this when working with <canvas>, or when you need the dimensions of an image for positioning, scaling etc.

In jQuery, using this is very simple:

$("img").on("load", function() {
  // do something

The problem with this is that Internet Explorer 9 has an annoying bug that prevents the onload event from firing for cached images. This means that your code works the first time the page is loaded, but if the user reloads it, it does not even run.

There are some solutions to this problem on the Internet, most of which have to do with appending a random string to the src attribute of the image. All of those solutions have two serious drawbacks:

  1. The entire image has to be reloaded from the server, increasing the amount of data your users have to download.
  2. Every time the image is requested, your server creates a copy of it in its internal cache, wasting precious space.

I have come up with a solution that does not have any of those disadvantages, and that is actually shorter and simpler than every workaround I have found. Again, in jQuery:

 $("img").attr("src", $("img").attr("src"));

As you can see, I am only setting the image’s src attribute to the exact same value it had before. That way, the browser does not download anything. If you watch this in the IE Dev Tools’ Network panel, you can see that the image isn’t even requested:

IE9 Network Panel

For some reason, however, this short line of code triggers the onload event.

I have yet to find any drawback that my solution has, but in case you run into one, please drop me a quick line in the comments!

About Author


Follow her/him on Twitter, Facebook or Google+!

Facebook Twitter

Send this to a friend