Loading Javascript Dynamically and how to check if the script exists
Listening for events on script elements is not considered reliable (Source). One option that comes to mind is to use setTimeout()
to poll for a variable that you expect to be defined in your external script. After x
seconds, you could timeout your poll and consider the script as broken.
External Script: file.js:
var MyLibrary = { };
Main document:
var poll;
var timeout = 100; // 10 seconds timeout
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'file.js';
document.body.appendChild(script);
poll = function () {
setTimeout(function () {
timeout--;
if (typeof MyLibrary !== 'undefined') {
// External file loaded
}
else if (timeout > 0) {
poll();
}
else {
// External library failed to load
}
}, 100);
};
poll();
It's pretty easy, Internet Explorer will trigger an onreadystatechange
event while others will trigger a onload
event for the script object.
var newScript;
var loadFunc = function ()
{
alert("External Javascript File has been loaded");
};
newScript = document.createElement('script');
newScript.setAttribute('type','text/javascript');
newScript.setAttribute('src','file.js');
//IE triggers this event when the file is loaded
if (elm.attachEvent)
{
newScript.attachEvent('onreadystatechange',function()
{
if (newScript.readyState == 'complete' || newScript.readyState == 'loaded')
loadFunc();
});
}
//Other browsers trigger this one
if (newScript.addEventListener)
newScript.addEventListener('load', loadFunc, false);
document.getElementsByTagName('head')[0].appendChild(newScript);
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "file.js";
You need to add a callback for this script.
1st: Create the call back:
function callbackFn(callbackArgs) = {
console.log("script is loaded with the arguments below");
console.log(callbackArgs);
}
2nd: Add an event listener to the script. Both Firefox and Chrome support onload event so you can use it like this:
script.onload = callbackFn();
For IE... You can add an event listener for a state change like this:
script.onreadystatechange = function() {
if ( this.readyState != "loaded" ) return;
callbackFn();
}
Last: Append the script to the body like you used to do.
document.body.appendChild(script);
For further information, please refer to this acticle.