DOMNodeInsertedIntoDocument on <body> element

DOMNodeInsertedIntoDocument on <body> element

本文关键字:element gt body lt on DOMNodeInsertedIntoDocument      更新时间:2023-09-26

我想"<body>创建的第一个时刻。我试过使用DOMNodeInserted/DOMNodeInsertedIntoDocument。下面是我的代码:

<html>
<head>
<script>
document.addEventListener("DOMNodeInserted", handleDomInserted, true);
document.addEventListener("DOMNodeInsertedIntoDocument", handleDOMNodeInsertedIntoDocument, true);
function handleDOMNodeInsertedIntoDocument(e) {
  console.log(e);
}
function handleDomInserted(e) {
  console.log(e);
}
</script> 
</head>
<body> 
<div id="foo">
  <span id="bazz"></span>
</div>
</body>
</html>

为什么这些函数永远不会被调用?

代码是正确的,但是当浏览器最初解析HTML时不会触发JavaScript事件。JS的even只会在DOM操作被JS完成时触发。

。如果在代码示例中添加以下内容,事件将触发:

<script>
var d = document.createElement('div');
d.innerHTML = 'test';
document.body.appendChild(d);
</script>