Include script files in one script file

Friday, 15. September 2017

The power of computing is to load a program from another program. Just like booting up the computer. To load an HTML page with many scripts files can be loaded with one script file.

After a few research, I found the following techniques:

1. create this master js file:
var tobeadded = document.createElement(’script’);//start script
tobeadded.src = ‘/script1.js’;//script src
document.head.appendChild(tobeadded);//close script
tobeadded = document.createElement(’script’);// repeat until all done
tobeadded.src = ‘/script2.js’;
document.head.appendChild(tobeadded);
tobeadded = document.createElement(’script’);// repeat until all done
tobeadded.src = ‘/script3.js’;
document.head.appendChild(tobeadded);

Save this file called master.js and enter this into the HTML file:
<script type=”text/javascript” src=”/master.js”></script>

The problem is that all the scripts will be loaded asynchronously, that is, you have no control which is loaded first. When one of the script depends on the other to be loaded first, you will experience error when scripts are executed “onload”.

2. Same problem as #1. You can need to add a script file first before adding this master file because of the reason mention before:
<script type=”text/javascript” src=”/jquery.js”></script>
It is because jquery.js is needed for all scripts in the master.js
Here is a different master.js file:
function include(file){
var script = document.createElement(’script’);
script.src = file;
script.type = ‘text/javascript’;
script.defer = true;
document.getElementsByTagName(‘head’).item(0).appendChild(script);
}
/* include any js files here */
include(‘/script1.js’);
include(‘/script2.js’);
include(‘/script3.js’);
This master.js is creating a function called include to ease the repetition.

3. This is what I prefer as I can control the order of the scripts loaded. Here is the inorder master.js file:
var scriptMap =["/jquery.js","/script1.js", "/script2.js", "/script3.js"];// list of to be loaded script in an array
var order = 0;
function loadScriptInOrder(){
if(order == scriptMap.length) {
return;
}
var JSLink = scriptMap[order];
var JSElement = document.createElement(’script’);
JSElement.src = JSLink;
JSElement.onload = callback;
document.getElementsByTagName(‘head’).item(0).appendChild(JSElement);

function callback(){
order++;
loadScriptInOrder();
}
};
loadScriptInOrder();//load the script in a recursive manner

This way I will not need to load jquery.js in HTML file and then inlude the master.js file. It will be one once and for all. That’s perfect!

Comments are closed.