Tutorial Fixing .load() in IE for cached images

by in , 0

The .load() function fires when the element it's called upon is fully loaded. It is commonly used on images, which may not be fully loaded when the JavaScript originally runs, and thus would return incorrect information about themselves (e.g. height/width). Most browsers deal with this fine. IE can cause problems, when images on the page are cached.

Selecting the image and changing it's src attribute to append a random parameter (based on the date). This will trick IE into firing the .load() function properly.

myImge = $("<img />")
   .attr("src",anyDynamicSource+ "?" + new Date().getTime());

Now the .load() function will work, even in IE:

$(myImge).load(function() {
   alert("will alert even in IE")
});
See the first comment for a warning about using this technique with a CDN.

Leave a Reply