0

I want to "catch" the very first moment when the <body> has created. I've tried using DOMNodeInserted / DOMNodeInsertedIntoDocument. here's my code:

<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>

Why do those functions never get called?
Thanks!

4

1 回答 1

5

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

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

<script>
var d = document.createElement('div');
d.innerHTML = 'test';
document.body.appendChild(d);
</script>
于 2013-06-12T15:09:10.993 回答