Reputation: 515
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:
Upvotes: 1
Views: 87
Reputation: 515
I resolved by writing an extra method to do an upfront check to see whether the passing parameter is Array or Object.
var multipleScript = function(_){
if (_ instanceof Array) {
_.map(function(o){
console.log(o);
loadScript(o);
})
} else if ( _ instanceof Object)
loadScript(_);
};
Now I can call, works fine, tested! But the downside of my solution is that, it has to be An Array [] inside! to apply same method to a set of objects.
multipleScript([{
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"]
}]);
Upvotes: 0
Reputation: 5167
You can make use of arguments
for example:
function loadScript() {
var length = arguments.length;
for (i = 0; i < length; i++) {
//do something
console.log(arguments[i])}
}
Upvotes: 1