Wait for the existence of the document.

I wrote a chrome extension that works before the page loads (using the attribute "run_at": "document_start"). The problem is that I want to add a tag divto the body of a web page right after it is created. Prior to this, document.bodyit is null, so I can not add tags to it.

I don’t care about the full load of the body, I just need it to exist.

I am trying to find a better way to be warned if a tag bodyin html is created (not fully loaded, just created). Is there any event handler for this case that I can write?

In addition, I do not want to use jQueryor any other non-built-in library.

Thank!

+4
source share
3 answers

You can use an event DOMContentLoadedthat looks like$(document).ready()

document.addEventListener("DOMContentLoaded", function(event) {
   console.log("DOM fully loaded and parsed");
});

MDN says

The event is DOMContentLoadedfired when it is documentfully loaded and analyzed, without waiting for the stylesheets, images, and subframes to complete loading (the event loadcan be used to detect a fully loaded page).

+5
source

You can use the mutational observer to document.documentElementlisten to changes in childListand see if the added item is being added 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>
+4

EDIT: as @michaelday explained this is actually bad practice because it uses a union that can take up valuable processor resources.

What is wrong if you use a very simple function?

/* This function waits until document.body exists*/
        function tryToAppend(node){
            if(!document.body){
                return setTimeout(tryToAppend.bind(null,node),1);
            }
            document.body.appendChild( node, document.body.firstChild );
        }
0
source

All Articles