Code:
/**
* 'asyncLoadScript'方法的配置项'options'的类型定义
* @typedef {Object} IOptions
* @prop {string} id - script标签的ID
* @prop {Function} onSucceed - 加载成功后的回调
* @prop {(Function|undefined)} onFailed - 加载失败后的回调
* @prop {boolean} strict - True: 'all'; False: 'allSettled';
*/
/**
* 异步加载JS脚本文件
* @param {string[]} scripts - JS文件路径列表
* @param {IOptions} options - 额外配置项
* @return {Promise}
*/
function asyncLoadScript(scripts, options) {
// 'scripts'参数不合法
if (!Array.isArray(scripts)) {
return Promise.reject(new Error('参数不合法'));
}
// 如果'scripts'参数长度为空,则直接结束
if (scripts.length === 0) {
console.warn('scripts 数组为空');
return Promise.resolve();
}
const docHead = document.querySelector('head');
// 处理<head>元素未找到的情况
if (docHead === null) {
return Promise.reject(new Error('未找到head标签'));
}
// 用于生产并加载script标签的promise数组
const scriptLoaderPromises = scripts.map(scriptPathname => {
return new Promise((resolve, reject) => {
const tag = document.createElement('script');
tag.setAttribute('src', scriptPathname);
typeof options?.id === 'string' && tag.setAttribute('id', options.id);
tag.setAttribute('async', true);
tag.addEventListener('load', () => resolve(tag));
tag.addEventListener('error', reject);
docHead.appendChild(tag);
});
});
// 选用的'Promise'静态方法名称('all', 'allSettled')
const staticMethodPropName = options?.strict === false ? 'allSettled' : 'all';
// *如果'options.onSucceed'方法未定义或不合法,则直接返回当前的promise,交由外部处理
if (typeof options?.onSucceed !== 'function') {
return Promise[staticMethodPropName](scriptLoaderPromises);
}
let failedHandler = options?.onFailed;
// 如果'options.onFailed'未定义,则会使用本地默认方法去处理错误情况
if (typeof failedHandler !== 'function') {
failedHandler = err => {
console.warn('asyncLoadScript 执行时出错:', err);
};
}
return Promise[staticMethodPropName](scriptLoaderPromises)
.then(options.onSucceed)
.catch(failedHandler);
}
标签:return,script,html,JS,tag,Promise,scripts,options,加载 From: https://www.cnblogs.com/fanqshun/p/17315399.html