图片队列下载

const handleDownload = () => {
if (!selectedImgIds.value.length) return Message.warning("请选择下载图片");
const downloadQueue = [...selectedImgIds.value];
let downloadingLen = 0;
const downloadProcess = () => {
if (downloadingLen >= 5) return; // 维持5个并发
if (!downloadingLen && !downloadQueue.length) {
// 下载完毕
loadingData.download = false;
Message.success("下载完成");
}
const preDownloadingQueue = downloadQueue.splice(0, 5 - downloadingLen);
selectedImgs.value.forEach(async (v) => {
if (preDownloadingQueue.includes(v.id)) {
downloadingLen++;
try {
await downloadFile({ url: v.img, title: v.fileName }); // 下载
const index2 = selectedImgs.value.findIndex((img) => v.id === img.id); // 下载完后将对应的选择框取消
selectedImgs.value.splice(index2, 1);
} finally {
// 防止失败仍占坑
downloadingLen--;
downloadProcess(v.id); // 递归
}
}
});
};
downloadProcess();
loadingData.download = true;
};

异步加载脚本

const reservation = {};

/**
* 异步加载脚本
* @param url 脚本地址
*/
export default function loadScript(url) {
if (!reservation[url]) {
reservation[url] = {
lock: false,
resolves: [],
};
}

if (reservation[url].lock) {
return new Promise((resolve) => {
reservation[url].resolves.push(resolve);
});
}

reservation[url].lock = true;

return new Promise((resolve) => {
const script = document.createElement("script");
script.type = "text/javascript";

if (script.readyState) {
// IE
script.onreadystatechange = () => {
if (
script.readyState === "loaded" ||
script.readyState === "complete"
) {
script.onreadystatechange = null;
resolve();
document.head.removeChild(script);
while (reservation[url].resolves.length) {
const callback = reservation[url].resolves.shift();
callback && callback();
}
}
};
} else {
// 其他浏览器
script.onload = () => {
resolve();
document.head.removeChild(script);
while (reservation[url].resolves.length) {
const callback = reservation[url].resolves.shift();
callback && callback();
}
};
}
script.src = url;
document.head.appendChild(script);
});
}