Reputation: 103
I have a script and need to expose functions so that these can be called from the page where the script is pasted.
For instance, the script thescript.js is:
console.log('The script has been loaded');
function doThisAPI() {
console.log('The API function has been called');
}
Now, the index.html where the script is placed is something like:
<html>
<head>
</head>
<body>
<script>
var s = document.createElement('script');
s.async = true;
s.src = '//thescript.js';
var s0 = document.getElementsByTagName('script')[0];
s0.parentNode.insertBefore(s, s0);
doThisAPI();
</script>
</body>
</html>
So, under normal circumstances, index.html would display both messages "The script has been loaded" and "The API function has been called".
However, if the script takes a time to load, the doThisAPI()
call would throw "Uncaught ReferenceError: doThisAPI is not defined".
How would you wrap the script so that API functions will always be executed only after the script has completely loaded?
Upvotes: 0
Views: 38
Reputation: 326
Add an eventlistener on script load and call doThisApi from that function.
var s = document.createElement('script');
s.async = true;
s.src = '//theScript.js';
var s0 = document.getElementsByTagName('script')[0];
s.addEventListener('load', function (e) {
doThisAPI();
}, false);
s0.parentNode.insertBefore(s, s0);
Upvotes: 1