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

查看:109
本文介绍了jQuery回调图像加载(即使图像被缓存)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

$("img").bind('load', function() {
  // do stuff
});

但是从缓存加载图像时不会触发加载事件。 jQuery docs 建议一个插件来解决这个问题,但它不起作用

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();
});

请注意 .bind() .one() 因此事件处理程序不会运行两次。

Note the change from .bind() to .one() so the event handler doesn't run twice.

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

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