在具体项目场景中,前端发版后,用户不手动刷新,则感知不到更新;经常会出现:前端更新了某个功能,导致旧功能使用出现问题,而被用户提单;
关于这个问题有多种解决方式:
- WebSocket ,需要后端配合
- 接口交互,需要后端配合
- nginx 配置
- 前端轮询是否更新(纯前端解决)
因为后端忙,所以暂时写了个纯前端的解决方案
import { ElMessage, ElMessageBox } from 'element-plus';
let lastSrcs = [] as any;
const scriptReg = /\<script.*src=["'](?<src>[^"']+)/gm;
async function getscript() {
const html = await fetch('/?temp=' + Date.now()).then(res => {
return res.text();
})
scriptReg.lastIndex = 0;
let result = []
let match;
//@ts-ignore
while((match = scriptReg.exec(html))) {
//@ts-ignore
result.push(match.groups.src)
}
return result
}
async function needUpdate() {
const newScripts = await getscript()
if(!lastSrcs.length) {
lastSrcs = newScripts
return false
}
let result = false;
if(lastSrcs.length !== newScripts.length) {
result = true
}
for(let i=0; i<lastSrcs.length;i++) {
if(lastSrcs[i] !== newScripts[i]) {
result = true;
break
}
}
lastSrcs = newScripts;
return result
}
const DURATION = 5000
function autoRefresh() {
setTimeout(async()=> {
const willUpdate = await needUpdate();
if(willUpdate) {
ElMessageBox.confirm(
'检测到系统有更新,是否立即更新?',
'系统提示',
{
confirmButtonText: '更新',
cancelButtonText: '稍后再说',
type: 'warning',
}
).then(() => {
window.location.reload()
}).catch(() => {
ElMessage.info('已取消,请稍后自己手动刷新页面',)
})
}
autoRefresh()
},DURATION)
}
autoRefresh()
再到 main.ts
中引入这个文件即可