Is the DOM ready when a script is executed within the body tree?

140 Views Asked by At

I have a snipped that is placed inside ANY website, in the middle of the document like in the middle of an article, not inside <head>. This script loads an external script on my domain by appending a <script> tag (pretty much like google analytics snippet does).

My questions is if that script is placed inside the body, does the DOM hasn't already been parsed, so I can safely assume that I can manipulate the DOM when my script is evaluated without waiting for DOMReady event?

I'm asking because theres a big delay when my script start executing and when the DOMReady event fires (see the brown bar). I'm using this DOMReady implementation

enter image description here

The Host Website

<html>

<head>
  ...
</head>

<body>
  Website content
  ...
  <div>
    
  <!-- Snippet -->
  <div id="myContainer"></div> <!------(I should be able to query this div) -->
  <script type="text/javascript">
    function() {
      var ga = document.createElement('script');
      ga.type = 'text/javascript';
      ga.async = true;
      ga.src = 'http://example.com/script.js';
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(ga, s);
    })();
  </script>
  <!-- Snippet End -->
  
  <div>
  More content
  ...
</body>
</html>

The example.com/ script.js

(function(){
    //by this time div#myContainer should exist, right?
    var div = document.getElementById('myContainer');
    div.innerHTML = "Hello World!";
})();

Some considerations:

  • I don't have control over the Host page, it can have anything inside it.
  • Support for old browsers are a concern.
  • I should be able to append stuff as soon as possible, I can't wait for things like other libraries, and images to finish loading.
  • It should reliable work everytime.
1

There are 1 best solutions below

0
Yaser On

Yes that's right. If you have a script tag at the bottom of the body, then by the time your script runs, everything is rendered before that.

W3Schools have a nice article on this subject.

Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, are placed in functions. Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.

Scripts in <body>

If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.