JavaScript - 覆盖.inload HTMLImageElement的原型 [英] JavaScript - overwriting .onload prototype of HTMLImageElement(s)
问题描述
是否可以将 onload 事件绑定到每个图像,并声明一次?我试过,但无法让它工作......(抛出此错误:未捕获TypeError:非法调用)
Is it possible to bind an onload event to each image, declaring it once? I tried, but can't manage to get it working... (this error is thrown: Uncaught TypeError: Illegal invocation)
HTMLImageElement.prototype.onload = function()
{
console.log(this, "loaded");
};
PS:我也试过返回这个,但似乎没有是这里的问题...对我目前的代码不起作用的任何建议/解释?
P.S: I also tried returning this, but doesn't seem to be the issue here... any suggestions / explanations on why my current code isn't working?
推荐答案
你不能在原型上设置一个处理程序,没有。
You can't set a handler on the prototype, no.
事实上,如果你没有挂钩,我不知道有任何方法可以获得图像加载的主动通知< load
不会冒泡。
In fact, I'm not aware of any way to get a proactive notification for image load if you haven't hooked load
on the specific image element, since load
doesn't bubble.
我只有两种方法可以实现一般的某些图像已经加载机制:
I only two know two ways to implement a general "some image somewhere has loaded" mechanism:
-
使用定时器循环,这显然在多个级别上不满意。但它确实起作用。实际查询(
document.getElementsByTagName(img)
)并没有那么糟糕,因为它返回对不断更新(实时)的引用HTMLCollection
img
元素,而非创建像querySelectorAll
的确如此。然后你可以在它上面使用Array.prototype
方法(如果你愿意的话,直接避免创建一个中间数组)。
Use a timer loop, which is obviously unsatisfying on multiple levels. But it does function. The actual query (
document.getElementsByTagName("img")
) isn't that bad as it returns a reference to the continually updated (live)HTMLCollection
ofimg
elements, rather than creating a snapshot likequerySelectorAll
does. Then you can useArray.prototype
methods on it (directly, to avoid creating an intermediary array, if you like).
使用变异观察器监视要添加的新 img
元素或现有的 src
属性 img
元素更改,然后挂钩加载
处理程序,如果他们的完成
属性不正确。 (你必须小心那里的竞争条件;即使你的JavaScript代码正在运行,浏览器也可以更改属性,因为你的JavaScript代码在单个UI线程上运行,但浏览器是多线程。)
Use a mutation observer to watch for new img
elements being added or the src
attribute on existing img
elements changing, then hook up a load
handler if their complete
property isn't true. (You have to be careful with race conditions there; the property can be changed by the browser even while your JavaScript code is running, because your JavaScript code is running on a single UI thread, but the browser is multi-threaded.)
这篇关于JavaScript - 覆盖.inload HTMLImageElement的原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!