checkUpdate
版本检查更新
配置项
| 参数 | 类型 | 是否必选 | 默认值 | 参数描述 |
|---|---|---|---|---|
| options | Object | 是 | - | 参数选项 |
| callback | Function | 是 | - | 版本落后执行的回调 |
返回值
| 类型 | 描述 |
|---|---|
| void | - |
示例
useCheckUpdate({pagePath: '/blog/', duration:5000})源码
js
export function checkUpdate(options = {pagePath: '/', duration: 2000}, callback) {
let lastScripts;
const scriptReg = /<script.*src=["'](?<src>[^"']+)/gm;
async function extractNewScripts() {
const fetchPath = `${options.pagePath}?_timestamp=${Date.now()}`
const html = await fetch(fetchPath).then(resp => resp.text())
scriptReg.lastIndex = 0;
let result = [];
let match;
while ((match = scriptReg.exec(html))) {
result.push(match.groups?.src);
}
return result;
}
async function needUpdate() {
const newScripts = await extractNewScripts();
if (!lastScripts) {
lastScripts = newScripts;
return false
}
let result = false;
if (lastScripts.length !== newScripts.length) {
result = true;
}
for (let i = 0; i < lastScripts.length; i++) {
if (lastScripts[i] !== newScripts[i]) {
result = true;
break;
}
}
lastScripts = newScripts;
return result;
}
function autoFresh() {
setTimeout(async () => {
const willUpdate = await needUpdate();
if (willUpdate) {
console.log('更新啦~')
callback()
} else {
console.log('已经是最新啦~')
autoFresh()
}
}, options.duration)
}
autoFresh()
}
@keyboarder-yang