[英]Wait for document.body existence
I wrote a Chrome extension that works before the page is loaded (using the attribute "run_at": "document_start"
).我编写了一个在页面加载之前工作的 Chrome 扩展程序(使用属性
"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.问题是我想在创建网页主体后立即将
div
标记添加到它。 Before that document.body
is null so I can't append tags to it.在该
document.body
为 null 之前,我无法向其附加标签。
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).我正在尝试找到在创建 html 中的
body
标签(未完全加载,刚刚创建)时收到警报的最佳方式。 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.另外,我不想使用
jQuery
或任何其他非内置库。
You 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
.您可以在
document.documentElement
上使用一个 突变观察者来监听其childList
变化,并查看添加的内容是否是body
。
<!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).ready()
DOMContentLoaded
事件
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
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).DOMContentLoaded
事件在document
完全加载和解析后触发,无需等待样式表、图像和子框架完成加载(load
事件可用于检测完全加载的页面)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.