JavaScript:了解图像何时完全加载

Pau*_*jan 19 javascript jquery image

如果我有一个灯塔:

<img src="http://example.com/beacon" />
Run Code Online (Sandbox Code Playgroud)

我希望在信标请求完成后调用一个方法.就像是:

<script>
    $("img.beacon").load(function() {
        // do stuff knowing the beacon is done
    });
</script>
Run Code Online (Sandbox Code Playgroud)

可能吗?它在jQuery中吗?

red*_*are 33

当然.请记住,需要在src属性之前添加负载.

$('<img />').load( function(){
  console.log('loaded');
}).attr('src', imgUrl);
Run Code Online (Sandbox Code Playgroud)

如果您已在标记中定义了图像标记,那么当窗口加载事件触发时您就会卡住,以确保图像已经下降到线上.


Pim*_*ger 18

$('img.beacon').load()
Run Code Online (Sandbox Code Playgroud)

不会总是正常工作,通常我这样做:

$.fn.imageLoad = function(fn){
    this.load(fn);
    this.each( function() {
        if ( this.complete && this.naturalWidth !== 0 ) {
            $(this).trigger('load');
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

上面的代码还包括在执行脚本之前图像已完成加载的情况.在标记中定义图像时可能会发生这种情况.

使用这样:

<img src='http://example.com/image.png' class='beacon' />
<script type='text/javascript'>
$(document).ready(function(){ //document.ready not really necessary in this case
   $('img.beacon').imageLoad(function(){
      //do stuff
   });
});
</script>
Run Code Online (Sandbox Code Playgroud)

  • 为什么$(this).get(0).naturalWidth而不是this.naturalWidth? (3认同)
  • 考虑在imageLoad()的末尾返回它,以便您可以链接.`$('img.beacon').imageLoad(function(){/*good*/}).error(function(){/*bad*/})` (2认同)