Calling Javascript file from another JavaScript file

Best of way to do this is using Document Object Model (DOM) , following simple function can perform this processing for this using DOM

function includeJavascriptFile(jsFileName,pos) {
var th = document.getElementsByTagName(pos)[0];
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src',jsname);
th.appendChild(s);
}

This function adds the necessary script tag into the end of the head or body section of the page for you. All that you then need to do from your Javascript in order to add another external javascript into the page is to call that function passing it the name of the file that contains the extra code that you want to include and whether to add it to the end of the head or the end of the body.

includeJavascriptFile('externalFile1.js','body');
includeJavascriptFile('externalFile2.js','head');

Once the script tags have been added to the page you can then call any functions that you want from within that file.

This method also useful to include the javascript files externally on the web page based on conditions like based on browser version include the different JS files

Another sample code for the above approach is

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



Following is another way to include the JS


<script type="text/javascript">
  document.write(unescape("%3Cscript src='" + (document.location.protocol == "https:" ? "https://testhttps" : "http://testhttp") + ".sivavaka.com/testJava.js' %3E%3C/script%3E"));
 </script>

No comments:

Post a Comment