网页动态加载js,优化首次加载性能
2024-01-29 本文已影响0人
戚培俊
/**
* @description 动态加载js
* @param url js地址
* @returns {Promise} 返回加载状态
*/
const loadScript =(url) => {
return new Promise((resolve, reject) => {
// 判断有没有加载过 有就不加载了
let scriptList = document.getElementsByTagName('script');
let isLoad = false;
for (let i = 0; i < scriptList.length; i++) {
if (scriptList[i].src === url) {
isLoad = true;
}
}
if (isLoad) {
resolve();
return;
}
// 动态加载js
let script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
script.onload = function () {
resolve();
};
})
}
使用
let isJsZipReady = ref(false)
loadScript(new URL('../utils/jszip.min.js', import.meta.url).href).then(() => {
console.info('jszip ready')
isJsZipReady.value = true
})