Javascript/jQuery: How to detect img is fully downloaded or not?

三世轮回 提交于 2019-12-04 09:38:25

You should be able to just bind your repositioning callback to the load event handler.

So in your last example:

$('#image1').load(function() {
     setPosition(); // without inspectSize() 
});

Where #image1 points to your image tag. Alternatively, as you mention the #image1 might just be a container then:-

$('#image1 img').load(function() {
     setPosition();
});

Update jfriend00 makes a good point below, in that 'load' will only fire when an image is added to the DOM, not if it already exists on the page at the time your JavaScript is run.

To cover both scenarios, you can do this:

var img = $('#image1');

if (img.prop('complete')) {
     setPosition();
} else {
     img.load(function() { setPosition(); });
}

The prop('complete') check will return true if the image already exists, and if it doesn't we bind the 'load' event handler.

a simple example is to bind the load event to the image. I always do the following

<img data-src="image.jpg" />

note that i don't set the src attribute yet

$(function() {
    $("img").each(function() {
        $(this).load(function() {
            alert('ready to call $(this).width()');
        }).prop("src", $(this).prop("data-src"));
    });
});

the .prop("src", $(this).prop("data-src")); set's the new src after the load event is binded

Shiv Kumar Ganesh

Try writing the same code inside.

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