JavaScript:知道图像何时完全加载

新手上路,请多包涵

如果我有信标:

 <img src="http://example.com/beacon" />

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

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

可能吗?它在 jQuery 中吗?

原文由 Paul Tarjan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 201
2 个回答

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

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

如果您已经在标记中定义了图像标签,那么您会在窗口加载事件触发时卡住,以确保图像已经通过网络传输。

原文由 redsquare 发布,翻译遵循 CC BY-SA 2.5 许可协议

$('img.beacon').load()

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

 $.fn.imageLoad = function(fn){
    this.on('load', fn);
    this.each( function() {
        if ( this.complete && this.naturalWidth !== 0 ) {
            $(this).trigger('load');
        }
    });
}

上面的代码还涵盖了在执行脚本之前图像已经完成加载的情况。当您在标记中定义图像时,可能会发生这种情况。

像这样使用:

 <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>

原文由 Pim Jager 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题