I have a function below to loadScript, aka loading css and js files into html document header and body while detecting and avoiding duplicates.
Initially, I use _.type as a switch condition but for that I have to define type: "js", when calling:
loadScript({
type: "js",
path: KERNEL +"/client/js/",
ref: ["script1.js"]
});
var loadScript = function(_){
console.log(_.ref);
var type = _.ref[0].slice(_.ref[0].lastIndexOf('.')+1);
console.log(type);
switch (type) {
case 'js':
_.ref.forEach(function(file){
var scripts = document.getElementsByTagName("script");
for(var i = 0; i < scripts.length; i++){
var src = scripts[i].getAttribute('src');
if(src)
if(src.indexOf(file) > -1){
return;
}
}
var link = document.createElement('script');
link.src = _.path + file;
link.type = 'text/javascript'; link.async = true; // async = false if you need scripts loaded in sequence!
document.getElementsByTagName('body')[0].appendChild(link);
});
break;
case 'css':
_.ref.forEach(function(file){
for(var i = 0; i < document.styleSheets.length; i++){
if(document.styleSheets[i].href.indexOf(file) > -1){
return;
}
}
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = _.path + file;
head.appendChild(link);
});
break;
default:
// code
}
};
So I set it to type instead of _.type in the switch to get rid of having to parse an additional parameter, BUT I can't do the following call:
loadScript({
path: KERNEL+"/client/js/",
ref: ["script1.js"]
}, {
path: PLUGIN_URL +"/js/",
ref: ["process1.js", "process2.js", "ui.js"]
},{
path: UTILS_BOWER_URL+"/client/css/",
ref: ["front2.css", "default.css"]
});
I don't want to have to do each (3x times):
loadScript({
path: KERNEL+"/client/js/",
ref: ["script1.js"]
});
loadScript({
path: PLUGIN_URL +"/js/",
ref: ["process1.js", "process2.js", "ui.js"]
});
References: