当用户页面在放置状态,我们的站点有刷新,这时候用户点击按钮或者跳转会出现报错的情况。其实这个是否需要用户去刷新界面加载最新的资源。so 下面是来自 袁老师 的思路
例如utils里面增加 autoUpdate.ts
let lastSrcs: Array<string | undefined>; //上一次获取到的script地址
const scriptReg = /\<script.*src=["'](?<src>[^"']+)/gm; // 匹配初次加载的html中script内容
// 执行获取所有script
async function extractNewScripts() {
const html = await fetch('/?_timestamp=' + Date.now())
.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 (!lastSrcs) { //初次不需要更新
lastSrcs = newScripts
return false
}
let result = false
if (lastSrcs.length !== newScripts.length) { // js文件集合不同了需要更新
result = true
}
for (let i = 0; i < lastSrcs.length; i++) { // 依次匹配script是否相同
const element = lastSrcs[i];
if (element !== newScripts[i]) {
result = true
break;
}
}
lastSrcs = newScripts
return result
}
const DURATION = 2000 // 默认检测的时间
function autoRefresh() { // 自动更新开启
setTimeout(async() => {
const willUpdate = await needUpdate()
if (willUpdate) {
const result = confirm('页面有更新,点击确定刷新页面')
if (result) {
location.reload()
}
}
autoRefresh()
}, DURATION);
}
autoRefresh()
然后在main 文件中引入即可
import '@/utils/autoUpdate';
以上是自动刷新的解决方案, 因为html中加载的内容是静态的内容不多,还有就是settime的时间是2秒性能完全不是问题的。