1.指标场景
有时候上完线,用户还停留在老的页面,用户不晓得网页重新部署了,跳转页面的时候有时候js连贯hash变了导致报错跳不过来,并且用户体验不到新性能。
2.思考解决方案
如何去解决这个问题
思考中…
如果后端能够配合咱们的话咱们能够应用webSocket 跟后端进行实时通信,前端部署完之后,后端给个告诉,前端检测到Message进行提醒,还能够在优化一下应用EvnentSource 这个跟socket很像只不过他只能后端往前端推送音讯,前端无奈给后端发送,咱们也不须要给后端发送。
以上计划须要后端配合,奈何公司后端都在忙,须要纯前端实现。
从新进行思考…
依据和小伙伴的探讨得出了一个计划,在我的项目根目录给个json 文件,写入一个固定的key值而后打包的时候变一下,而后代码中轮询去判断看有没有变动,有就提醒。
果然是康老师经典不晓得。
然而写完之后发现太麻烦了,须要手动配置json文件,还须要打包的时候批改,有没有更简略的计划,
进行第二轮探讨。
第二轮探讨的计划是依据打完包之后生成的script src 的hash值去判断,每次打包都会生成惟一的hash值,只有轮询去判断不一样了,那肯定是重新部署了.
3.代码实现
interface Options {
timer?: number
}
export class Updater {
oldScript: string[] //存储第一次值也就是script 的hash 信息
newScript: string[] //获取新的值 也就是新的script 的hash信息
dispatch: Record<string, Function[]> //小型公布订阅告诉用户更新了
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(/<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/ig) //script正则
return html.match(reg) as string[] //匹配script标签
}
//公布订阅告诉
on(key: 'no-update' | 'update', fn: Function) {
(this.dispatch[key] || (this.dispatch[key] = [])).push(fn)
return this;
}
compare(oldArr: string[], newArr: string[]) {
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 up = new Updater({
timer:2000
})
//未更新告诉
up.on(‘no-update’,()=>{
console.log(‘未更新’)
})
//更新告诉
up.on(‘update’,()=>{
console.log('更新了')
})
复制代码
4.测试
执行 npm run build 打个包
装置http-server
应用http-server 开个服务
从新打个包npm run build
这样子就能够检测进去有没有从新公布就能够告诉用户更新了。
发表回复