所有浏览器的图像加载时的JavaScript / jQuery事件监听器 [英] JavaScript/jQuery event listener on image load for all browsers

查看:211
本文介绍了所有浏览器的图像加载时的JavaScript / jQuery事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来为尽可能多的浏览器实现这一点:

I am looking for a way to implement this for as many browsers as possible:

var image = new Image();
image.addEventListener("load", function() {
                               alert("loaded");
}, false);
image.src = "image_url.jpg";

这在IE中不起作用所以我用Google搜索并发现IE低于9不支持 - 阅读进度 - ()。我知道有一个名为 .bind()的jQuery等价物,但这不适用于 Image()。我还需要改变什么才能在IE中工作?

This didn't work in IE so I googled and found out that IE's lower than 9 do not support .addEventListener(). I know there is a jQuery equivalent called .bind() but that doesn't work on an Image(). What do I have to change for this to work in IE too?

推荐答案

IE支持attachEvent。

IE supports attachEvent instead.

image.attachEvent("onload", function() {
    // ...
});

使用jQuery,你可以写

With jQuery, you can just write

$(image).load(function() {
    // ...
});

说到事件,如果你有可能使用jQuery我建议使用它,因为它将负责浏览器兼容性。您的代码适用于所有主流浏览器,您不必担心。

When it comes to events, if you have the possibility of using jQuery I would suggest using it because it will take care of browser compatibility. Your code will work on all major browser and you don't have to worry about that.

另请注意,为了在IE中触发加载事件,您需要确保图像不会从缓存中加载,否则IE不会触发加载事件。

Note also that in order to the load event being fired in IE, you need to make sure the image won't be loaded from the cache, otherwise IE won't fire the load event.

为此,您可以附加一个虚拟变量你的图片网址的结尾,像这样

To do this, you can append a dummy variable at the end of the url of your image, like this

image.setAttribute( 'src', image.getAttribute('src') + '?v=' + Math.random() );

使用jQuery加载方法的一些已知问题是

Some known issues using the jQuery load method are


与图像一起使用时加载事件的注意事项

Caveats of the load event when used with images

开发人员尝试使用.load()$ b $解决的常见挑战b快捷方式是在图像(或
图像集合)完全加载时执行函数。有几个已知的注意事项,需要注意
。这些是:

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:


  • 它不能始终如一地工作,也不能可靠地跨浏览器

  • 它没有'如果图像src设置为
    与之前相同的src,则在WebKit中正确触发

  • 它没有正确地冒泡DOM树

  • 对于已经存在于浏览器的
    缓存中的图片可以停止触发

  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree
  • Can cease to fire for images that already live in the browser's cache

有关详细信息,请参阅 jQuery docs

See the jQuery docs for more info.

这篇关于所有浏览器的图像加载时的JavaScript / jQuery事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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