My script file needs to dynamically import another script and utilize the functions and variables defined inside it.
Currently, I am adding it to the HEAD
section of the Page. However, after the addition, the functions and variables from the outer script are not fully loaded and available for use. How can I ensure that the script is completely loaded?
I have attempted to use script.onreadystatechange
and script.onload
callbacks, but I am encountering some browser compatibility issues.
What is the safest way to achieve this with pure JS while maintaining decent browser compatibility?
Sample:
uno.js:
var script = document.createElement("script");
script.src = "dos.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
alert(outerVariable); // undefined
dos.js:
var outerVariable = 'Done!';
sample.html
<html>
<head>
<script type="text/javascript" src="uno.js"></script>
</head>
...
</html>