欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2023年01月15日 09:26:46   作者:小滿zs  
這篇文章主要為大家介紹了JS前端重新部署通知用戶刷新網(wǎng)頁示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

1.目標(biāo)場景

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

2.思考解決方案

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

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

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

重新進(jìn)行思考...

根據(jù)和小伙伴的討論得出了一個方案,在項(xiàng)目根目錄給個json 文件,寫入一個固定的key值然后打包的時候變一下,然后代碼中輪詢去判斷看有沒有變化,有就提示。

果然是康老師經(jīng)典不知道。

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

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

3.代碼實(shí)現(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標(biāo)簽
    }
    //發(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)
    }
}

代碼用法

//實(shí)例化該類
const up = new Updater({
    timer:2000
})
//未更新通知
up.on('no-update',()=>{
   console.log('未更新')
})
//更新通知
up.on('update',()=>{
    console.log('更新了')
})

4.測試

執(zhí)行 npm run build 打個包

安裝http-server

使用http-server 開個服務(wù)

重新打個包npm run build

這樣子就可以檢測出來有沒有重新發(fā)布就可以通知用戶更新了。

以上就是JS前端重新部署通知用戶刷新網(wǎng)頁的詳細(xì)內(nèi)容,更多關(guān)于JS通知用戶刷新網(wǎng)頁的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論