admin管理员组文章数量:1255020
I wrote a Chrome extension that works before the page is loaded (using the attribute "run_at": "document_start"
).
The problem is that I want to add a div
tag to the web page body as soon as it is created.
Before that document.body
is null so I can't append tags to it.
I don't care about full load of the body, I just need it to be existent.
I am trying to find the best way to be alerted when the body
tag in html is created (not loaded fully, just created). Is there any event handler for this case that I can write?
Also, I don't want to use jQuery
or any other non built-in library.
I wrote a Chrome extension that works before the page is loaded (using the attribute "run_at": "document_start"
).
The problem is that I want to add a div
tag to the web page body as soon as it is created.
Before that document.body
is null so I can't append tags to it.
I don't care about full load of the body, I just need it to be existent.
I am trying to find the best way to be alerted when the body
tag in html is created (not loaded fully, just created). Is there any event handler for this case that I can write?
Also, I don't want to use jQuery
or any other non built-in library.
2 Answers
Reset to default 23You could use a mutation observer on document.documentElement
listening for changes to its childList
and looking to see whether the thing that got added is body
.
Example: Live Copy
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<script>
(function() {
"use strict";
var observer = new MutationObserver(function() {
if (document.body) {
// It exists now
document.body.insertAdjacentHTML(
"beforeend",
"<div>Found <code>body</code></div>"
);
observer.disconnect();
}
});
observer.observe(document.documentElement, {childList: true});
})();
</script>
</head>
<body>
<div id="foo"></div>
</body>
</html>
You can use DOMContentLoaded
event which is similar to $(document).ready()
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
MDN says
The
DOMContentLoaded
event is fired when thedocument
has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (theload
event can be used to detect a fully-loaded page).
本文标签: javascriptWait for documentbody existenceStack Overflow
版权声明:本文标题:javascript - Wait for document.body existence - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738245361a2071115.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论