javascript - 将 image.src 设置为自身会导致 onLoad 触发吗?

标签 javascript dom dom-events

我似乎无法找到这个问题的明确答案......

假设我有一个对页面上图像的 JavaScript 引用,并且我将 load 事件处理程序绑定(bind)到该元素。例如,像这样:


HTML

<img id="myImage" src="http://example.com/image.jpg" />

JavaScript

var $myImage = $('#myImage');
$myImage.load(function() {
    alert('Image loaded!')
});

现在,如果我这样做:

var imageElem = $myImage[0];
imageElem.src = imageElem.src; // Re-assign the image source path

...load 事件处理程序是否会触发即使图像已经从服务器加载?在 Firefox 中似乎是这样,但依赖这种行为是否安全?

(我问的原因是我看到它在 jQuery 插件中用于检查何时加载了所有图像。如果图像在 load 事件处理程序绑定(bind)之前加载,那么它不会触发,除非使用上述方法重新触发。)

最佳答案

设置 img.src 应该触发加载,但有一些注意事项。根据jQuery自己的documentation regarding the .load event ,

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

关于javascript - 将 image.src 设置为自身会导致 onLoad 触发吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13864545/

相关文章:

dom - 在 Prototype 中使用 $$ 是不是不好?

javascript - 如何重置 jquery 应用的内联 css?

javascript - 获取可能通过 Angular 范围的所有事件的列表。 $$听众数?

JavaScript .hashchange 性能。它能带来任何放缓吗?

javascript - 如何验证元素是否存在于 CucumberJS 和 Protractor 中?

javascript - 尝试向 JavaScript 输出添加前导 "$"

javascript - 如何在纯javascript中创建多个div(createElement)

javascript - 如何使用 Word 2016 的 Javascript API 在 ContentControl 上实现 OnEnter 和 OnExit 事件

javascript - Firefox 中未定义事件

javascript - Overlay div 链接到相同的相关 div 目标地址