Pseudo code of what I am trying to accomplish:
if(in dev environment){
//write unminified scripts to the head tag
}
else{ // in production
// write the minified distribution script to the head
}
Option 1.) Works intermittently in Chrome desktop browser and intermittently in Safari Mobile.
function write_to_head (path ,js_file_src){
var js_script = document.createElement('script');
js_script.type = "text/javascript";
js_script.src = path + js_file_src;
document.getElementsByTagName('head')[0].appendChild(js_script);
}
Option 2.) Works 100% of the time in Chrome and works intermittently in Safari Mobile. Also seem to work better when async:false , but this is a no no since it could possibly block user interaction .
function load_script(path ,js_file_src){
$.ajax({
async:true, // false may block user interaction
type:'GET',
url:path +""+ js_file_src,
data:null,
cache: true,
success:_onsuccess,
error: _onerror,
dataType:'script'
});
The I call one of the following functions based on whether I'm in a dev or production environment.
var dev_scripts = ["script1.js","script2.js","script3.js",........etc];
var prod_scripts = ["all-dist.min.js",........etc];
function load_dev(){
for(var i=0;i<dev_scripts.length;i++){
// call write_to_head ("/api/path/",dev_scripts [i] );
// or
// load_script("/api/path/",dev_scripts [i] );
}
}
function load_prod(){
for(var i=0;i<prod_scripts .length;i++){
// call write_to_head ("/api/path/",prod_scripts [i] );
// or
// load_script("/api/path/",prod_scripts [i] );
}
}
Is there a better way to accomplish what I discussed above across all browser for mobile and desktop ?
There are a couple of potential answers, depending on your constraints and design.
Okay - This is the canonical way to manually append the files from the client side, without any external libraries. You are replicating a "tag manager", which is a service that manages these listings for you. BrightTag is an example of a vendor that does exactly this.
More preferably, one would use something like require.js to load in dependencies, assuming that (1) you have all the scripts on the same domain as the page (avoiding CORS issues) and (2) that they can be loaded asynchronously.
Best-practices would dictate that you use require.js correctly, and design all of your modules to follow the AMD specification.
In the development case, you would use the <script src="some/require.js"
data-main="my/root/file.js"></script>
pattern described in those docs, which loads the require.js library, which then loads your root module, which then pulls in all other declared dependencies before execution.
In production case, you would use the require.js packaging tool (r.js or similar) to compile the files into one file. The tool uses your choice of uglify.js or Google Closure Compiler to minify and concatenate all the files, just like you (apparently) have done already.
Good luck!