How to Load External JavaScript Asynchronously or Dynamically


JavaScript makes more easier to manipulate websites, now a days most of the browsers supporting JavaScript codes. When the HTML parser encounters a

The defer attribute causes the browser to defer execution of the script until after the document has been loaded and parsed and is ready to be manipulated. The async attribute causes the browser to run the script as soon as possible but not to block document parsing while the script is being downloaded. If a

I have placed this code at the bottom of HTML codes, i.e. just before tag and have placed the following code where I want to display ads.



Loading JavaScript Asynchronously when document finishes loading 




You can load and execute scripts asynchronously by using setTimeout(), addEventListner(), and attachEvent(). Most objects that can be event targets have a method named addEventListner(), which allows the registration of multiple listeners.

window.addEventListner("load", function(){.....},false);
request.addEventListner("readystatechange", function(){......},false);

The first argument to this function is the name of the event. For IE8 and earlier, you must use a similar method, named attachEvent().

window.attachevent("onload", function() {.....});

Here is an example which define an onLoad() function that registers a function to be run when the document finishes loading. If the document has already loaded, run it asynchronously.

function onLoad(f){
if(onLoad.loaded)
window.setTimeout(f,0);
elseif (window.addEventListner)
window.addEventListner("load",f,false);
elseif (window.attachEvent)
window.attachEvent("onload",f);
}

onLoad.loaded=false;

onLoad(function(){onLoad.loaded=true;});


In the above script window.attachEvent is used for IE8 and earlier. onLoad.loaded=false; sets a flag that indicates the document is not loaded yet and onLoad(function(){onLoad.loaded=true;}); register a function to set the flag when the document does load.



Related Posts: