3

i have around 5 to 6 JavaScript which i put it at the bottom of page however I wanted to load all this JavaScript in one function so all of them download on the page Asynchronously. Can anyone suggest how can i do that? Some syntaxes will definitely helpful

`

JqueryGuy
  • 51
  • 1
  • 4

1 Answers1

5

On newer browsers you can use the async attribute:

<scritp src="yourscript.js" type="text/javascript" async=true ></script>

Or for wider support you can append the script to an already processed tag in the document:

Edit:

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);
}

And you can load them like so:

loadScript('script1.js');
loadScript('script2.js');
loadScript('script3.js');
loadScript('script4.js');
Ibu
  • 42,752
  • 13
  • 76
  • 103
  • 1
    While useful, I don't think that this is what the OP is asking. That said, I forgot about the async attribute so I found it interesting :) – David L Mar 18 '13 at 18:39
  • You are right, there is a second option – Ibu Mar 18 '13 at 18:41
  • the above is only for one script how about another 4 external js file?? – JqueryGuy Mar 18 '13 at 18:47
  • loadScript('script1.js'); loadScript('script2.js'); like that in above javascript function? sorry i am bit confuse here?? if you can give me syntax would be great help...sorry i don't know much JS – JqueryGuy Mar 18 '13 at 18:51
  • You can call them anyway you want – Ibu Mar 18 '13 at 18:52
  • tell me if this is the right method it gives me error "ss is not defined " – JqueryGuy Mar 18 '13 at 19:00
  • You have a typo on your code. you have `ssa` instead of `ss`, other than that everything is fine, see my updated code – Ibu Mar 18 '13 at 19:52