jQuery or JavaScript: Determine when image finished loading

 ̄綄美尐妖づ 提交于 2019-11-27 04:25:18

问题


How can I detect when an image has finished loading be it from the server or the browser cache? I want to load various images in the same <img/> tag and detect when the loading of a new images has finished.

Thank you.


回答1:


$('img').on('load', function() {
    // do whatever you want
});



回答2:


The onload document's event will fire only after all the elements, images included, have fully loaded.

The onload <img>'s event will fire after the single image have fully loaded.

So you can attach a listener to these events, using jQuery objects or DOM's addEventListener (and IE's attachEvent)




回答3:


Well, this is quite an old thread I came across yesterday. I'm using backbone.js and require.js and resizing my layout always caused problems with views that contain images.

So, I needed a way to know when the last image has finished loading to resize the layout. All, mentioned solutions above didn't work in my case. After some hours of more investigation I found the ultimate solution that is working:

http://desandro.github.com/imagesloaded/

Hope that helps others as well.




回答4:


I think this looks a bit cleaner

$('img').load(function() {
    // Your img has finished loading!
});



回答5:


For a more thorough image load detection, including images loaded from cache, try this: https://github.com/paulirish/jquery.imgloaded




回答6:


From a very similar question Official way to ask jQuery wait for all images to load before executing something and just like Pikrass says:

With jQuery, you use $(document).ready() to execute something when the DOM is loaded and $(window).load() to execute something when all other things are loaded as well, such as the images.

Here are two examples:

DOM

jQuery(document).ready(function(){
    console.log('DOM ready');
});

Images / Everything Else

jQuery(window).load(function(){
    console.log('all other things ready');
});

You should be able to confirm in your console:

screenshot-with-shadow.png http://img547.imageshack.us/img547/9681/yih.png




回答7:


Everyone mentioned that the event should be fired before set to the src.

But if you don't want to worry about it, you can use the oncomplete event (will be fired even with cached images) to fire onload, like this:

$("img").one("load", function() {
  // do stuff
}).each(function() {
  if(this.complete) $(this).load();
});

Using jQuery you don't have to worry about backward compatibility (eg: img.height>0 in IE)



来源:https://stackoverflow.com/questions/4494437/jquery-or-javascript-determine-when-image-finished-loading

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