javascript - 为什么没有调用 document.onload ?

标签 javascript

通过查看 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会显示为一个属性呢?这是由于GlobalEventHandlersDocument includes GlobalEventHandlers ),并且由于 event handler IDL attribute ,将它们公开为 on... 事件属性。

关于javascript - 为什么没有调用 document.onload ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72591323/

相关文章:

javascript - promise 重试设计模式

javascript - useRef 当前仅在第二次更新时获取其值

Javascript 搜索栏过滤器,在页面上隐藏/显示

javascript - 插入动态生成的表格单元格时无法识别 anchor 标记

javascript - jquery onclick 从 div 到 div

javascript - 3d 变换 : DOM order taking priority over z-transform

javascript - 使用 Ajax 和 PHP 上传音频文件

javascript - Adobe CEP 扩展(indesign) : Is it possible to call "js" function from "jsx"?

javascript - 替换数组特定键值中的子字符串

javascript - JavaScript 中的全局变量