<body>元素上的DOMNodeInsertedIntoDocument

cap*_*gon 0 html javascript dom javascript-events

我想"抓住" <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>
Run Code Online (Sandbox Code Playgroud)

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

mar*_*ful 5

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

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

<script>
var d = document.createElement('div');
d.innerHTML = 'test';
document.body.appendChild(d);
</script>
Run Code Online (Sandbox Code Playgroud)