Working with jQuery load() function on images in Internet Explorer 8 and below

by Cedric Dugas on November 9, 2011

One big problem with using load() on images is that it just does not work at all on IE. Now there is a lot of solutions proposed to counter this problem but unfortunately most of them are irritating.

Why IE handle load() this way

Simple, IE already cached your image, why should it need to load it back? The 2 most know solution to this are 1, adding a random string at the end of the image url, like this:

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

The other solution is to check the height property since if it’s not zero, the image is already loaded:

$('img').each(function() {
    if ($(this).height() > 0) {
       our callback
    } else {
       $(this).load(function() {
         our callback
       });
    }
});

Well these 2 solutions work, but they are not really nice. In fact this problem can be solved in a much better way.

Use load() first

Yup. That’s it, when you create your image in javascript, before doing anything else use your load function and IE will behave like all the other browsers.

$("<img>").load(function(){
     // do stuff
  }).attr({
	"id":"imgInsert",
	"src":response.url,
	"alt":response.alt
);


5 comments

You should use this.complete or $(this).prop(‘complete’) instead of height(). It’s meant specifically for this purpose.

by Blaise Kal on November 11, 2011 at 11:03 am. Reply #

Thank you for this post, I’m a webdeveloper and I really like I have to develop everything 2 times:
first time for every good browser
second time for every IE :)

by Alex on January 16, 2012 at 5:47 am. Reply #

Thanks a lot, it’s work fine !!!!!!!!!!

by Wondernanne on February 6, 2012 at 4:36 am. Reply #

Thanks a lot :)

by nasrin on July 12, 2012 at 2:32 am. Reply #

$(“”).load(function(){
// do stuff
}).attr({
“id”:”imgInsert”,
“src”:response.url,
“alt”:response.alt
);

this don’t work in ie

by nataliya on October 18, 2012 at 6:23 am. Reply #

Leave your comment

Required.

Required. Not published.

If you have one.