有时候上完线,用户还停留在老的页面,用户不知道网页重新部署了,跳转页面的时候有时候js连接hash变了导致报错跳不过去,并且用户体验不到新功能。
讨论的方案是根据打完包之后生成的script src 的hash值去判断,每次打包都会生成唯一的hash值,只要轮询去判断不一样了,那一定是重新部署了.
代码实现
interface Options {
timer?: number
}
export class Updater {
oldScript: string[] //存储第一次值也就是script 的hash 信息
newScript: string[] //获取新的值 也就是新的script 的hash信息
dispatch: Record //小型发布订阅通知用户更新了
constructor(options: Options) {
this.oldScript = [];
this.newScript = []
this.dispatch = {}
this.init() //初始化
this.timing(options?.timer)//轮询
}
async init() {
const html: string = await this.getHtml()
this.oldScript = this.parserScript(html)
}
async getHtml() {
const html = await fetch('/').then(res => res.text());//读取index html
return html
}
parserScript(html: string) {
const reg = new RegExp(/