[英]Why isn't document.onload called?
通过查看console.log(document)
的输出,我发现document
具有以下属性: onload=null;onloadstart=null;onloadend=null;onreadystatechange=null;
我写了以下代码:
<html>
<head><title>test</title></head>
<body>
<script>
document.onload=function(){alert("document.onload");};
document.onloadstart=function(){alert("document.onloadstart");};
document.onloadend=function(){alert("document.onloadend");};
document.onreadystatechange=function(){alert("document.onreadystatechange");};
</script>
<div>hello</div>
</body>
</html>
有趣的是, document.onload,document.onloadstart,document.onloadend
从来没有被调用过,而document.onreadystatechange
被调用了两次,为什么?
为什么不调用 document.onload?
首先, load
事件(由浏览器创建)不会冒泡(因为它是这样指定的):
document.body.onload = function(e) { console.dir(e.bubbles) }
因此,您只能在它们发生的元素上侦听这些load
事件。
对于Document ,没有列出将根据标准触发的load
事件。
另一方面, readystatechange
被列为document
可能发生的事件。
但是,您可以肯定地监听document
上的load
事件,并且将调用事件回调。 但这只有在您手动触发document
时才会发生:
const event = new Event('load'); document.onload = function (e) { console.log('load document') } document.dispatchEvent(event);
或者,如果您发出一个在后代上冒泡的load
事件:
const event = new Event('load', {bubbles: true}); document.onload = function (e) { console.log('load document') } document.body.dispatchEvent(event);
那么为什么onload
会作为一个属性出现呢? 这是由于GlobalEventHandlers
和Document includes GlobalEventHandlers
),并且由于事件处理程序 IDL 属性,将它们公开为on…
事件属性。
.onload
是window
对象的一部分,而不是document
。 GlobalEventHandlers.onload
GlobalEventHandlers mixin 的 onload 属性是一个事件处理程序,用于处理
Window
、XMLHttpRequest
、<iframe>
和<img>
元素等上的load
事件。
从我在 MDN 上看到的.onloadstart
和.onloadend
用于图像等资源,不知道它们是否可用于document
/ window
。 GlobalEventHandlers.onloadstart
但我认为使用onreadystatechange
您应该能够模拟onloadstart
和onloadend
的行为。
Document.readyState
我不确定,但试试这个:
window.addEventListener('load', () => {
alert("document.onload")
})
我只使用 window onload 事件,但如果我从未见过 document onload 事件,只需将window
更改为document
。
就像我说的那样,我不确定该怎么做,因为您显示的代码量要少。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.