How can I dynamically load and execute a JavaScript file, and then ensure that its functions and variables are available in the current scope?
Specifically, I want to load a remote JavaScript file at runtime, and then use its exported functions and variables in my application. However, since the file is loaded asynchronously, I can’t simply include it with a tag and assume that everything will be available when I need it.
What is the best way to accomplish this in JavaScript, and how can I ensure that my code waits until the remote file has finished loading before attempting to use its exports?
Assuming we have a remote JavaScript file named remote.js with the following content:
// remote.js
export function foo() {
console.log("Hello from remote.js");
}
And we have an HTML file with the following content:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Dynamic JavaScript loading example</title>
</head>
<body>
<h1>Dynamic JavaScript loading example</h1>
<script>
function loadScript("https://example.com/remote.js") {
const script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
document.head.appendChild(script);
foo(); // I want to ensure that this function is available in the current scope.
}
</script>
</body>
</html>
2
Answers
Write it as a module. Use a dynamic import.
remote.js:
If the URL to the JS file is constant (i.e. not dynamically determined) you can use a regular
import
instead.Note that since your example code uses an absolute URL, you might be requesting the script across origins. If so then you will need CORS permission.
Useful background reading: JavaScript Modules, MDN.
Add callback function
onload