开发者

jquery: image width on domready or load?

hey guys, I'm using the jquery data() method to store the width of images.

When is jquery able to get the width of images. on-dom-ready or on-load? Is it necessary to have the images loaded to query it's width, or can i query the width on domready as开发者_如何学Go well?

thank you

this is my piece of code:

    //Save the original image width
    $(".post-body img").each(function() {  
        $(this).data('width', $(this).width());
    });


It depends, if you're specifying the width, then DOM ready works fine. If you're depending on the width coming from the image itself, you need to check once it's loaded, using window.onload which fires after images are loaded, for example:

$(window).load(function() {
  var w = $("img").width();
});


If all of your images are coming in when the page loads and you are sure that none are going to be loaded after (as a result of ajax calls or something) Nick's answer will work fine. Otherwise, it is a bit tougher. Here is the event I bind to for image load event for such cases:

https://github.com/peol/jquery.imgloaded/pull/4#diff-0

It's still a work in progress since this is a tough problem...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜