admin管理员组

文章数量:1186285

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.

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.

Share Improve this question edited Jan 23, 2013 at 10:05 Denys Séguret 382k90 gold badges809 silver badges775 bronze badges asked Jan 20, 2013 at 21:40 user1597002user1597002
Add a comment  | 

2 Answers 2

Reset to default 30

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';

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....

本文标签: javascriptonload callback on image not called in ie8Stack Overflow