关于图像加载 IE 问题的 JavaScript/jQuery 事件监听器

标签 javascript jquery dom-events image-load

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

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

这在 IE 中不起作用,所以我用 google 搜索,发现 IE 低于 9 不支持 .addEventListener()。我知道有一个名为 .bind() 的 jQuery 等效项,但它不适用于 Image()。我需要更改什么才能使其在 IE 中也正常工作?

最佳答案

IE 支持 AttachEvent。

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

使用 jQuery,您只需编写即可

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

说到事件,如果您有可能使用 jQuery,我建议您使用它,因为它将照顾浏览器兼容性。您的代码将在所有主要浏览器上运行,您不必担心这一点。

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

为此,您可以在图像网址末尾附加一个虚拟变量,如下所示

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

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

Caveats of the load event when used with images

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:

  • 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了解更多信息。

关于关于图像加载 IE 问题的 JavaScript/jQuery 事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7442821/

相关文章:

javascript - 对于刚上传到 Meteor GridFS 的图像,第一个请求返回 503

javascript - 延迟鼠标滚轮功能

jquery - Coldfusion CFC 在 Jquery 中返回 JSON 显示,如何处理来自 CFC 的多条记录并在 Jquery 中显示?

javascript - 如何消除水平滚动条?

javascript - 使用 Javascript 添加两个数字时犯了什么错误

javascript - Firefox 和 IE8 中的 onKeyPress 事件

javascript - 根据值过滤对象属性

javascript - Xpath:获取节点属性

javascript - jQuery fadeIn div 显示

javascript - 具有 onblur 监听器的 Chrome 打包应用程序