Categories
JavaScript

Include Javascript file inside another

This can be really handy sometimes, in Javascript there’s no way of including or importing other JS files.

For example in my case I want it to include the JQuery file from the CDN of Google, but I didn’t want to use another typical call to an external file.

What I did is inside of the common JS library of my project add this:

var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://code.jquery.com/jquery-1.4.2.min.js';
head.appendChild(script);

With tihs simple trick we added the script to the HTML header.

Of course you can use a function if you are going to use it a lot:

function includeJs(jsFile) {
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= jsFile;
head.appendChild(script);
}

includeJs('http://code.jquery.com/jquery-1.4.2.min.js');

This is based in the new way google is going to use for analytics:

 var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

As you can see they also use the attribute async.