Sunday, 7 June 2015

Load multiple javascript files asynchronously

load multiple javascript files asynchronously



In Every website, We have to include the JavaScript. We need to include multiple JavaScript file in single web page.

It's always prefer to include the javascript at the bottom of the page so that loading of content remain fast. So we should add at the bottom of the page.

We should also load the JavaScript files asynchronously, means load JavaScript file parallel.


There are two ways to load JavaScript file. Newer browsers have async attribute which load JavaScript asynchronously.
<scritp async="true" src="yourscript.js" type="text/javascript"></scritp>

Use custom JavaScript function to load javascript-file asynchronously.


<script type="text/javascript">
function loadScript (scriptpath){
    var s=document.getElementsByTagName('script')[0];
    var ss=document.createElement('script');
    ss.type='text/javascript';
    ss.async=true;
    ss.src= scriptpath;
    s.parentNode.insertBefore(ss,s);
}
</script>

Just call the loadScript function to load javascript file asynchronously. For Example.
<script type="text/javascript">
loadScript('/js/jQueryJSFIle1.js');
loadScript('/js/jQueryJSFIle2.js');
loadScript('/js/jQueryJSFIle3.js');
</script>