title: Dynamically load external Javascript file, and wait for it to load - without using JQuery
body: <p>I'm trying to dynamically load an external .js file (according to an input I get from the user).
  Currently my code looks like this:</p>
  
  <pre><code>function createScript(src, id) {
      if (document.getElementById(id) == null) {
          var newScript = document.createElement('script');
          newScript.setAttribute("type", "text/javascript");
          newScript.setAttribute("src", src);
          newScript.setAttribute("id", id);
          document.getElementsByTagName("head")[0].appendChild(newScript);
      }
  }
  </code></pre>
  
  <p>This kind of work. It does load the script, but if I try to call a function that is defined inside the new script it won't work. The weird thing is if I wait for a second (using an <code>alert("test")</code> or something like that) the script does work.</p>
  
  <p>I guess its because the browser adds the <code>&lt;script&gt;</code> tag immediately, but it takes it a little longer to "read" the script inside of the .js file.
  I tried playing with <code>"typeof testfunction === 'function'"</code> with a few variations but no luck.</p>
  
  <p>Any good way of doing this?</p>