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):
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
following the suggestion here:
https://stackoverflow.com/a/7308984/300741
I set the async
and defer
attributes to false
, 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.
What am I missing here? Note that if I use setTimeout()
to wait a bit before calling myFun()
it works as expected, so it's definitely an async/deferred loading problem... but how do I fix it? (using Chrome by the way)