我似乎无法找到这个问题的明确答案......
假设我有一个对页面上图像的 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/