图像加载时的 jQuery 回调(即使图像被缓存) [英] jQuery callback on image load (even when the image is cached)

查看:29
本文介绍了图像加载时的 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.

这篇关于图像加载时的 jQuery 回调(即使图像被缓存)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆