图像加载 IE 问题上的 JavaScript/jQuery 事件侦听器 [英] JavaScript/jQuery event listener on image load IE issues

查看:29
本文介绍了图像加载 IE 问题上的 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 中不起作用,所以我用谷歌搜索并发现 IE 低于 9 不支持 .addEventListener().我知道有一个名为 .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 中触发 load 事件,您需要确保不会从缓存中加载图像,否则 IE 不会触发 load 事件.

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() 解决的常见挑战快捷方式是在图像(或图像的集合)时执行一个函数图像)已完全加载.有几个已知的警告这是应该注意的.它们是:

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
  • 它没有正确地冒泡 DOM 树
  • 可以停止为浏览器中已经存在的图像触发缓存

有关详细信息,请参阅 jQuery 文档.

See the jQuery docs for more info.

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

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