前端重新部署如何通知用户刷新网页?
我把我掘金的文章同步一份給CSDN?
1.目標場景
有時候上完線,用戶還停留在老的頁面,用戶不知道網(wǎng)頁重新部署了,跳轉(zhuǎn)頁面的時候有時候js連接hash變了導(dǎo)致報錯跳不過去,并且用戶體驗不到新功能。
2.思考解決方案
如何去解決這個問題 思考中...
如果后端可以配合我們的話我們可以使用webSocket 跟后端進行實時通訊,前端部署完之后,后端給個通知,前端檢測到Message進行提示,還可以在優(yōu)化一下使用EvnentSource 這個跟socket很像只不過他只能后端往前端推送消息,前端無法給后端發(fā)送,我們也不需要給后端發(fā)送。
以上方案需要后端配合,奈何公司后端都在忙,需要純前端實現(xiàn)。
重新進行思考...
根據(jù)和小伙伴的討論得出了一個方案,在項目根目錄給個json 文件,寫入一個固定的key值然后打包的時候變一下,然后代碼中輪詢?nèi)ヅ袛嗫从袥]有變化,有就提示。
果然是康老師經(jīng)典不知道。
但是寫完之后發(fā)現(xiàn)太麻煩了,需要手動配置json文件,還需要打包的時候修改,有沒有更簡單的方案, 進行第二輪討論。
第二輪討論的方案是根據(jù)打完包之后生成的script src 的hash值去判斷,每次打包都會生成唯一的hash值,只要輪詢?nèi)ヅ袛嗖灰粯恿?#xff0c;那一定是重新部署了.
3.代碼實現(xiàn)
interface Options {timer?: number }export class Updater {oldScript: string[] //存儲第一次值也就是script 的hash 信息newScript: string[] //獲取新的值 也就是新的script 的hash信息dispatch: Record<string, Function[]> //小型發(fā)布訂閱通知用戶更新了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 htmlreturn html}parserScript(html: string) {const reg = new RegExp(/<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/ig) //script正則return html.match(reg) as string[] //匹配script標簽}//發(fā)布訂閱通知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.lengthconst 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)}} 復(fù)制代碼代碼用法
//實例化該類 const up = new Updater({timer:2000 }) //未更新通知 up.on('no-update',()=>{console.log('未更新') }) //更新通知 up.on('update',()=>{console.log('更新了') }) 復(fù)制代碼4.測試
執(zhí)行 npm run build 打個包
安裝http-server
使用http-server 開個服務(wù)
重新打個包npm run build
這樣子就可以檢測出來有沒有重新發(fā)布就可以通知用戶更新了。
總結(jié)
以上是生活随笔為你收集整理的前端重新部署如何通知用户刷新网页?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 5. 创建视图vw_vp:查询小米Not
- 下一篇: flex垂直居中,最简单的方法之一