场景
上线后,用户还停在老页面,不知道网页已经重新部署了,所以不能体验新功能
解决
- 跟后端协商,使用websocket实时通讯,部署完后,后端给个通知
- 纯前端解决,轮询去判断服务端的index.html是否跟当前的index.html的脚本hash值一样,思路如下
js脚本
/* eslint-disable */
export class Updater {
constructor(options = {}) {
this.oldScript = []
this.newScript = []
this.dispatch = {}
this.init() //初始化
this.timing(options.time)//轮询
}
async init() {
const html = await this.getHtml()
this.oldScript = this.parserScript(html)
}
async getHtml() {
const html = await fetch('/').then(res => res.text());//读取index html
return html
}
parserScript(html) {
const reg = new RegExp(/<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/ig) //script正则
return html.match(reg) //匹配script标签
}
//发布订阅通知
on(key, fn) {
(this.dispatch[key] || (this.dispatch[key] = [])).push(fn)
return this;
}
compare(oldArr, newArr) {
const base = oldArr.length
// 去重
const arr = Array.from(new Set(oldArr.concat(newArr)))
//如果新旧length 一样无更新
if (arr.length === base) {
this.dispatch['no-update'].forEach(fn => {
fn()
})
} else {
//否则通知更新
this.dispatch['update'].forEach(fn => {
fn()
})
}
}
timing(time = 10000) {
//轮询
setInterval(async () => {
const newHtml = await this.getHtml()
this.newScript = this.parserScript(newHtml)
this.compare(this.oldScript, this.newScript)
}, time)
}
}
调用
const upDater = new Updater({
time: 5000
})
upDater.on('no-update', () => {
console.log('还没更新')
})
upDater.on('update', () => {
console.log('已经更新了,请刷新页面')
})