3

I have some external JS code that needs to run asynchronously. The way I call it is I create a script inside an asynchronous function which I then attach to the rest of the scripts on the page like so..

<script type="text/javascript">
 (function() {
   var second = document.createElement('script'); 
   second.type = 'text/javascript'; 
   second.async = true;
   second.src =  "http://myserver.com/second.js";
   var scripts = document.getElementsByTagName('script')[0];    
   scripts.parentNode.insertBefore(second, scripts);
       })();
   </script>

Now suppose there was another script (first.js) which also needs to run asynchronously but it needs to run before this script (second.js), how can I chain them together to ensure first.js is already loaded when second.js runs?

Not sure if I should go with jQuery getScript or if there was a simpler way?

Some code examples based on what I provided would be greatly appreciated.

Community
  • 1
  • 1
AbuMariam
  • 3,282
  • 13
  • 49
  • 82
  • 1
    Can use a module loader like [requirejs](http://requirejs.org/) otherwise create promise chains bound to load handlers – charlietfl Aug 10 '15 at 16:05
  • If it's not essential that you handle this entirely on the client-side, you might consider building a simple server-side script compiler/aggregator ... Potentially leveraging [Google's Closure Compiler API](https://developers.google.com/closure/compiler/docs/gettingstarted_api?csw=1). – svidgen Aug 10 '15 at 16:24

0 Answers0