js 纯前端实现 重新部署 通知用户刷新网页

需求:有时候上完线,用户还停留在老的页面,用户不知道网页重新部署了,跳转页面的时候有时候js连接hash变了导致报错跳不过去,并且用户体验不到新功能,需要进行优化,每当打包发版后客户进入系统就要提示系统更新,提示客户。

解决: public上整一个json文件,然后每次打包的时候改变这个json第一次我拿到了ison的数据存起来,然后轮询请求,直到json 数据上这个时间变化了,我提示用户。

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

在这里插入图片描述
代码实现 : 自定义一个js 或 ts 文件
RedeployMessage.ts
把下边的代码复制粘贴进去

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)
    }
}

然后呢?—在最外层的App文件内引用这个ts 文件 。

如果是vue项目,放在onMoutend钩子函数

//实例化该类
const up = new Updater({
    timer:2000
})
//未更新通知
up.on('no-update',()=>{
   console.log('未更新')
})
//更新通知
up.on('update',()=>{
    console.log('更新了')
}) 

在这里插入图片描述

如果是react 项目可以放在componentDidMount()

//实例化该类
const up = new Updater({
    timer:2000
})
//未更新通知
up.on('no-update',()=>{
   console.log('未更新')
})
//更新通知
up.on('update',()=>{
    console.log('更新了'),更新进行提示弹框消息。自己封装就好了,一般都有组件直接用
}) 

在这里插入图片描述
在这里插入图片描述

注意有可能出现的问题,就是提示更新了但是客户一直不点击更新,然后页面就会在定时后发送一次弹框信息,此时我们要记得清除定时器 clearInterval()。
即 在轮询的时候赋值一个变量

 timing(time = 10000) {
     //轮询
  let clearTime =   setInterval(async () => {
        const newHtml = await this.getHtml()
        this.newScript = this.parserScript(newHtml)
        this.compare(this.oldScript, this.newScript)
    }, time)
}

然后再调用定时器的地方,清除,即 
//否则通知更新
        this.dispatch['update'].forEach(fn => {
            fn()
            clearInterval(this.clearTime)
        })

还有一种方案可以看看这个博主写的,进入。我没试。欢迎来撩骚

猜你喜欢

转载自blog.csdn.net/lzfengquan/article/details/131451542