Image does not have width at document.ready

随声附和 提交于 2019-11-29 16:06:25

Here's an ultra-safe way to do it that doesn't require waiting for all the images to load, and takes care of situations where the image may be cached or finished loading before the DOM is ready.

$('#my_img').one('load',function(){
    resizeImgByArea('logo', 50);
})
  .filter(function(){
     return this.complete;
})
  .load();

  • .one('load',...) removes the handler as soon as it is invoked. You only need it once.

  • .filter() will return the image if it was already loaded. If not, it returns no elements.

  • .load() will manually invoke the handler. This will only occur if the image was already loaded.


So if the image was preloaded before the DOM was ready, we'll invoke its .load() handler manually. If not, its handler will be invoked when it is loaded.

From the jQuery docs on the jQuery(callback) method:

This function behaves just like $(document).ready()

And when we go to the docs on $(document).ready(), we find this:

Description: Specify a function to execute when the DOM is fully loaded.

So it's actually doing what it's supposed to. It isn't waiting for other resources (such as images) to load; it's executing your callback as soon as the DOM is ready.

You could get that <img> element and attach a load event listener, but what if the image really did finish loading, before you could attach it? Your callback will never be executed.

It's not pretty, but I think the safest thing you can do is just wait for the entire page to finish loading:

$(window).load(function () {
    resizeImgByArea('logo', 50);
});
mrtsherman

Images are not loaded at document.ready time. Instead use the .load() method of jQuery.

$('#logo').load( function() {
    resizeImgByArea('logo', 500);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!