In many instances Javascript file needs to be loaded dynamically when its required.
This minimizes the overhead of hude javascript file on page load.
The below "loadScript" can be used to load a external javascript file to current web document.
This function can be called on any javascript event.
The below function creates script tag of required js with required attribute and appends it to the document head tag.
callbackfunction is called only after the js file is completely loaded.
This is assured by oScript.onreadystatechange on IE and oScript.onload on firefox browser.
function loadScript(sScriptSrc,callbackfunction)
{
//gets document head element
var oHead = document.getElementsByTagName('head')[0];
if(oHead)
{
//creates a new script tag
var oScript = document.createElement('script');
//adds src and type attribute to script tag
oScript.setAttribute('src',sScriptSrc);
oScript.setAttribute('type','text/javascript');
//calling a function after the js is loaded (IE)
var loadFunction = function()
{
if (this.readyState == 'complete' || this.readyState == 'loaded')
{
callbackfunction();
}
};
oScript.onreadystatechange = loadFunction;
//calling a function after the js is loaded (Firefox)
oScript.onload = callbackfunction;
//append the script tag to document head element
oHead.appendChild(oScript);
}
}
Sample for using loadScript function is given below
var SuccessCallback = function(){
fnInsideDynamicJs();
}
<input type="button" onclick="loadScript('/js/requiredjsfile.js',SuccessCallback)" />
On the button click "/js/requiredjsfile.js" is loaded first and fnInsideDynamicJs() function inside the requiredjsfile.js is called.