我正在寻找一种方法来为尽可能多的浏览器实现此功能:
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/