user1597002
user1597002

Reputation:

onload callback on image not called in ie8

I'm trying to preload image and set the height and width to a container.

The problem seems to be with caching in ie8 since it fails to load on subsequent refreshes.

I've looked up and tried multiple solutions but seems nothing is working, at least not consistently.

current Javascript:

    img = new Image();
    img.src = '/images/site/image.jpg';
    img.onload=function(){
        var width = img.width + 'px';
        var height = img.height + 'px';

        $('#container').css({'width':width,
                          'height':height
        });
    };

Any suggestions are appreciated, thanks.

Upvotes: 9

Views: 6133

Answers (2)

Hank
Hank

Reputation: 1678

This is how retarded ie7 and ie8 are, even after setting the src AFTER the onload event, the event listener still misses it.

Check this out, this is what I finally had to do for one of my projects - ready for this? Settimeout. Yup! That's how retarded you have to write your code to get things to "work" in ie.

myImage.onload = doSomething;

var slowMeDown = setTimeout(function(){
                      myImage.src = "img/somePic.jpg";
                 },300);

Un-freaking-believable....

Upvotes: 4

Denys Séguret
Denys Séguret

Reputation: 382150

You must set the onload callback before setting the src.

When the image is cached, the onload callback isn't called with your code as the load event is produced before the callback is set.

Do this :

img = new Image();
img.onload=function(){
    var width = img.width + 'px';
    var height = img.height + 'px';

    $('#container').css({'width':width,
                      'height':height
    });
};
img.src = '/images/site/image.jpg';

Upvotes: 30

Related Questions