wait for document.body existence

前端 未结 2 1619
清歌不尽
清歌不尽 2020-12-09 21:34

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

相关标签:
2条回答
  • 2020-12-09 21:59

    You can use DOMContentLoaded event which is similar to $(document).ready()

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

    MDN says

    The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

    0 讨论(0)
  • 2020-12-09 22:13

    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>
    
    0 讨论(0)
提交回复
热议问题