图像加载时的 jQuery 回调(即使图像被缓存)
问题描述:
我想做:
$("img").bind('load', function() {
// do stuff
});
但是从缓存加载图像时不会触发加载事件.jQuery 文档 建议 一个插件来解决这个问题,但是它不起作用
But the load event doesn't fire when the image is loaded from cache. The jQuery docs suggest a plugin to fix this, but it doesn't work
答
如果 src
已经设置,那么事件在缓存的情况下被触发,甚至在你绑定事件处理程序之前.要解决此问题,您可以循环检查和触发基于 .complete
的事件,如下所示:
If the src
is already set, then the event is firing in the cached case, before you even get the event handler bound. To fix this, you can loop through checking and triggering the event based off .complete
, like this:
$("img").one("load", function() {
// do stuff
}).each(function() {
if(this.complete) {
$(this).load(); // For jQuery < 3.0
// $(this).trigger('load'); // For jQuery >= 3.0
}
});
注意从 .bind()
到 .one()
所以事件处理程序不会运行两次.
Note the change from .bind()
to .one()
so the event handler doesn't run twice.