通过查看 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
被调用了两次,为什么?
最佳答案
Why isn't document.onload called?
首先,load
事件(由浏览器创建)不会冒泡(因为它是这样指定的):
document.body.onload = function(e) {
console.dir(e.bubbles)
}
因此,您只能在发生这些 load
事件的元素上监听这些事件。
对于 Document没有列出将根据标准触发的 load
事件。
readystatechange
另一方面被列为 document
可能发生的事件。
但是,您可以肯定地监听 document
上的 load
事件,并且将调用事件回调。但这只有在你例如在文档
上手动触发:
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
),并且由于 event handler IDL attribute ,将它们公开为 on...
事件属性。
关于javascript - 为什么没有调用 document.onload ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72591323/