const LIST = [
'script',
'css',
]
function appendDependencies() {
const jsList = [
'xxxx.xxxx.js',
]
const cssList = [
'xx.css'
]
const fragment = document.createDocumentFragment();
// add js
_append(jsList, fragment);
// // add css
_append(jsList, fragment, 'css');
document.querySelector('head').appendChild(fragment);
}
function _append(obj, root, type = 'script') {
if (!LIST.includes(type)) {
throw new Error(`type must be one of ${LIST.join(',')} !`);
}
// loop the list to append each child
if (Array.isArray(obj)) {
return obj.forEach(item => {
_append(item, root, type);
});
}
let _node;
// specialized each item's type
switch(type) {
case 'script':
_node = document.createElement('script');
_node.setAttribute('type', 'text/javascript');
break;
case 'css':
_node = document.createElement('link');
break;
}
_node.setAttribute("charset", "utf-8");
_node.setAttribute("href", obj);
root.appendChild(_node);
return;
}