等待 document.body 存在 [英] Wait for document.body existence

查看:23
本文介绍了等待 document.body 存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个 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.

推荐答案

你可以使用 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 存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆