Saturday, March 31, 2012

Fixing .load() in IE for cached images

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")
});



I was struggling with this issue on one of the sites I’m making and actually there’s a bit better way to fixing this. It turn out the bug is fixed if you add “load” first and only after that change “src” for the image.
So actually the best way would be to
$('img').load(function() { ... }).attr('src', 'new_image_source'); 
it worked for me as a charm on multiple runs for the same already cached images.
Have a nice day





No comments: