Dynamically include JavaScript files
by Vijay[ Edit ] 2009-08-20 12:30:43
Some times we may have two different js files but only one of them will be used/accessible by your program .
Usally you will include two js files in the program and them you will call the functions from either of the file.
for eg;
<script language=javascript src="../menu-bar.js"></script>
<script language=javascript src="../tooltip.js"></script>
But if you know that only one of the js file will be used , then you can use like this,
var fno = 1; // store or get or set the value for which file should be loaded
var oScript = document.createElement("script");
if(fno==1)
oScript.src = "../menu-bar.js";
else
oScript.src = "../tooltip.js";
document.body.appendChild(oScript);
This will load either one of the files and this will reduce the time to load all the javascript files to the cache and the pages will be faster to load even at the first time.
Note:
But there is a drawback in this method.
You can not assure that the file is loaded or not. For example if the js file is not present at the specified location it wont alert or render a 404 error. You have to use it once you make sure that the js files are present and present without any error.