前端重新部署通知用户刷新网页

(一)背景

有时候上线上好了,但用户还在用旧版,一般只有刷新之后,重新请求了网络资源才能拿到新的资源。而且旧版js的hash指向又变了,容易收到一些没必要的bug报告。

(二)解决方案

1.websocket

如果有后端配合,使用websocket就可以做到,后端给个通知,前端检测到 Message 进行提示,还可以在优化一下使用 EvnentSource 这个跟 socket 很像只不过他只能后端往前端推送消息,前端无法给后端发送,我们也不需要给后端发送。

这个需要后端配合,纯前端怎么实现呢?

2.麻烦点,轮询+人工修改

我们自己在public上整一个json文件,文件里面写入一个key值,打包的时候自己去修改一下,然后在项目里面第一次拿到的时候存起来,后面轮询这个值,发生变化的话就提示刷新。

3.切入点,每次打包都会给文件打上一个新的hash值

根据打完包之后生成的 script src 的hash值去判断,每次打包都会生成唯一的 hash 值,只要轮询去判断不一样了,那一定是重新部署了。
在这里插入图片描述

(三)代码实现

这里需要实现一个简单的发布订阅模式

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('更新了')
})
  1. 测试
    执行 npm run build 打个包

安装 http-server

使用 http-server 开个服务

image.png

重新打个包 npm run build

image.png

这样子就可以检测出来有没有重新发布就可以通知用户更新了。

参考文章:前端重新部署如何通知用户刷新网页?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值