前端重新部署如何通知用戶刷新網(wǎng)頁?

1.目標場景

有時候上完線,用戶還停留在老的頁面,用戶不知道網(wǎng)頁重新部署了,跳轉(zhuǎn)頁面的時候有時候js鏈接hash變了導致報錯跳不過去,并且用戶體驗不到新功能。

2.思考解決方案

如何去解決這個問題 思考中...

如果后端可以配合我們的話我們可以使用webSocket 跟后端進行實時通訊,前端部署完之后,后端給個通知,前端檢測到Message進行提示,還可以再優(yōu)化一下使用EvnentSource 這個跟socket很像只不過他只能后端往前端推送消息,前端無法給后端發(fā)送,我們也不需要給后端發(fā)送。

以上方案需要后端配合,奈何公司后端都在忙,需要純前端實現(xiàn)。

重新進行思考...

根據(jù)和小伙伴的討論得出了一個方案,在項目根目錄給個json 文件,寫入一個固定的key值然后打包的時候變一下,然后代碼中輪詢?nèi)ヅ袛嗫从袥]有變化,有就提示。

但是寫完之后發(fā)現(xiàn)太麻煩了,需要手動配置json文件,還需要打包的時候修改,有沒有更簡單的方案, 進行第二輪討論。

第二輪討論的方案是根據(jù)打完包之后生成的script src 的hash值去判斷,每次打包都會生成唯一的hash值,只要輪詢?nèi)ヅ袛嗖灰粯恿?,那一定是重新部署?

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 html
        return 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.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('
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容