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. var th = document.getElementsByTagName(pos)[0];
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src',jsname);
th.appendChild(s);
}
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.includeJavascriptFile('externalFile2.js','head');
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