动态加载js 动态加载css 判断是否加载完成 判断是否已经引入了某js css文件
//动态加载 js
function loadScript(url,callback) {
const script = document.createElement('script');
script.type = 'text/javascript';
script.onload = function () {
callback();
}
script.src = url;
document.body.append(script);
}
调用时:
调用时:
loadScript(url,function () {
//...加载完成后执行的代码 });
// 动态加载css并返回加载成功回调
function loadStyles(url) {
function superviseCssLinkLoad(link, onload) {
requestIdleCallback(() => {
if (link.sheet) {
if (link.sheet.cssRules?.length) {
typeof onload === 'function' && onload()
} else {
superviseCssLinkLoad(link, onload)
}
} else {
superviseCssLinkLoad(link, onload)
}
})
}
return new Promise((resolve, reject)=>{
const themeLink = document.createElement('link');
themeLink.id = '__theme_link__';
themeLink.rel = 'stylesheet';
themeLink.href = url;
const head = document.getElementsByTagName('head');
if (head && head.length) {
head[0].appendChild(themeLink);
superviseCssLinkLoad(themeLink, () => { resolve() })
}
})
},
调用时:
loadStyles(url).then(()=>{
//...加载完成后执行的代码
});
//判断是否引入了js css文件
function isInclude(name){
let js= /js$/i.test(name);
let es=document.getElementsByTagName(js?'script':'link');
for(let i=0;i<es.length;i++) {
if(es[i][js?'src':'href'].indexOf(name)!=-1) return true;
}
return false;
},
//调用时
console.log('aaa.css') //false
console.log('aaa.css') //false
console.log('aaa.js') //false
if(!this.isInclude(name)){
}