title: Javascript: waiting for dynamically loaded script to be ready
body: <p>I'm using the following code to load a script dynamically in an html page (since I don't know the URL before serving the page):</p>
  
  <pre><code>let script = document.createElement('script');
                  script.src = 'https://foo/bar/myscript.js';
                  script.async = false;
                  script.defer = false;
                  document.head.appendChild(script);
  
                  //Try to use a global function defined in the script:
                  myFun(); //This raises "undefined" error
  </code></pre>
  
  <p>following the suggestion here: 
  <a href="https://stackoverflow.com/a/7308984/300741">https://stackoverflow.com/a/7308984/300741</a>
  I set the <code>async</code> and <code>defer</code> attributes to <code>false</code>, to be sure that the script loads before I try to use it. But as you can see from the comment in the last line of code, this is not working.</p>
  
  <p>What am I missing here? Note that if I use <code>setTimeout()</code> to wait a bit before calling <code>myFun()</code> it works as expected, so it's definitely an async/deferred loading problem... but how do I fix it? (using Chrome by the way)</p>