我编写了一个 Chrome 扩展程序,可以在页面加载之前运行(使用属性 run_at":document_start").问题是我想在创建后立即将 div 标记添加到网页正文.在那之前 document.body 是空的,所以我不能给它附加标签.
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.
我正在尝试找到在创建 html 中的 body 标记(未完全加载,只是创建)时发出警报的最佳方法.我可以为这种情况编写任何事件处理程序吗?
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?
另外,我不想使用 jQuery 或任何其他非内置库.
Also, I don't want to use jQuery or any other non built-in library.
你可以使用 document.documentElement 上的 ">mutation observer 监听对其 childList 的更改并查看添加的内容是否为 body.
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.
示例: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>
这篇关于等待 document.body 存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 Angular 2/Typescript 中使用 IScrollUse IScroll in Angular 2 / Typescript(在 Angular 2/Typescript 中使用 IScroll)
Anime.js 在 Ionic 3 项目中不起作用anime.js not working in Ionic 3 project(Anime.js 在 Ionic 3 项目中不起作用)
Ionic 3 - 使用异步数据更新 ObservableIonic 3 - Update Observable with Asynchronous Data(Ionic 3 - 使用异步数据更新 Observable)
Angular 2:在本地 .json 文件中找不到文件Angular 2: file not found on local .json file(Angular 2:在本地 .json 文件中找不到文件)
在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指In Ionic 2, how do I create a custom directive that uses Ionic components?(在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指令?)
将 ViewChild 用于动态元素 - Angular 2 &离子2Use ViewChild for dynamic elements - Angular 2 amp; ionic 2(将 ViewChild 用于动态元素 - Angular 2 amp;离子2)