The code below runs on a page:
(function() {
function asyncLoad() {
var urls = ["https://something.com/script.js"];
for (var i = 0; i < urls.length; i++) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = urls[i];
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
}
window.attachEvent ? window.attachEvent('onload', asyncLoad) : window.addEventListener('load', asyncLoad, false);
})();
//]]>
I need an event listener that fires when this file is available in the DOM.
I need to utilize variables from this script.
I need to know when https://something.com/script.js has been loaded and if it is not I would like a backup to fire. This can happen if the file hasn’t loaded within a designated period of time.
Alternatively I could use an event for when a variable is available from the script.js file.
Script elements support the load event, so you should set the listener on the script element before inserting it in the DOM, e.g.
If you want to know if it arrived successfuly or not, use XMLHttpRequest to get the content, then assign it to the script element’s text property. That way you can know if the script was retreived, set a timeout in case of failure and take corrective action and not lock the browser in the meantime.