I am using the following technique to load up Javascript dynamically:
var script = document.createElement(\"script\");
script.type = \"text/javascript\";
scr
In the onload event, there are status codes. 200 is good, 404 as you may recall means a file is not found. Helpful?
Loading a script dynamically is much more simple:
var script = document.createElement('script');
script.onload = function () {
main_function(); // Main function to call or anything else or nothing
};
script.src = "yourscript.js";
document.head.appendChild(script);
What JavaScript library do you use?
In jQuery if you load the script via Ajax, you have an option to run a success callback function (and other types of callbacks)...
There is also a dedicated function for loading scripts: $.getScript()
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);
You can append an onload
attribute and in that attribute, you can call a function which will be executed after the JS file has loaded.
Check the code:
var jsElement = document.createElement("script");
jsElement.type = "application/javascript";
jsElement.src = "http://code.jquery.com/jquery-latest.min.js";
jsElement.setAttribute("onload","getMeAll()");
document.body.appendChild(jsElement);
function getMeAll(){
//your code goes here
}
Hope this helps.
One way would be to define a variable in the script you include and then check whether this variable is defined, or not.