繁体   English   中英

为什么不调用 document.onload?

[英]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会作为一个属性出现呢? 这是由于GlobalEventHandlersDocument includes GlobalEventHandlers ),并且由于事件处理程序 IDL 属性,将它们公开为on…事件属性。

.onloadwindow对象的一部分,而不是document GlobalEventHandlers.onload

GlobalEventHandlers mixin 的 onload 属性是一个事件处理程序,用于处理WindowXMLHttpRequest<iframe><img>元素等上的load事件。

从我在 MDN 上看到的.onloadstart.onloadend用于图像等资源,不知道它们是否可用于document / window GlobalEventHandlers.onloadstart

但我认为使用onreadystatechange您应该能够模拟onloadstartonloadend的行为。
Document.readyState

我不确定,但试试这个:

window.addEventListener('load', () => {
    alert("document.onload")
})

我只使用 window onload 事件,但如果我从未见过 document onload 事件,只需将window更改为document

就像我说的那样,我不确定该怎么做,因为您显示的代码量要少。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM