Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

javascript - Wait for document.body existence

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...