title: JS: When do dynamically inserted scripts get executed?
body: <p>I want to do an AJAX call at the top of the head and once it is done, insert a script with its content depending on the result of the ajax call. Something like this:</p>
  
  <pre><code>var request = new XMLHttpRequest();
    request.open('GET', 'https://mypage.com/');
    request.setRequestHeader('Accept', 'application/json');
    request.onreadystatechange = function () {
      if (this.readyState === 4 &amp;&amp; this.status === 200) {
        var result = JSON.parse(this.responseText);
        if (result.foo === 'bar') {
          insertScript('bar');
        } else {
          insertScript('not bar');
        }
      }
    };
    request.send();
  }
  </code></pre>
  
  <p>Insert Script code:</p>
  
  <pre><code>function insertScript (msg) {
    var script = document.createElement("script");
    var content = "console.log('" + msg + "');";
    var inlineScript = document.createTextNode(content);
    script.appendChild(inlineScript);
    document.head.appendChild(script);
  }
  </code></pre>
  
  <p>So now I am wondering: <strong>When does the script gets executed?</strong> I want it to execute as fast as possible. It gets attached to the head. What if the dom-parser already reached the body? Will it stop and execute the new script in the head first? Will it render everything and then execute the script?</p>