中小型发布订阅通告客户升级了 constringth 一样无

lxf2023-03-16 13:51:01

中小型发布订阅通告客户升级了 constringth 一样无

1.总体目标情景

有时上完了线,客户只停留在老页面,客户不清楚网页页面重新配置了,跳转页面时有时js联接hash发生变化造成出错跳不过去,而且客户体验不上特色功能。

2.思索解决方法

怎样去解决这些问题 思考中...

假如后面也可以使用我们的话我们可以使用webSocket 跟后面开展实时通讯,前面布署完以后,后面给个通告,前面检测出Message开展提醒,也可以在提升一下应用EvnentSource 这个跟socket特别像只不过是他只好后面向前端推送消息,前面没法给后面推送,大家不需要给后面推送。

之上计划方案必须后面相互配合,怎奈企业后面都在忙,必须纯前面完成。

再次深入思考...

依据和小伙伴们的探讨总结出了一个计划方案,在工程网站根目录给个json 文档,载入一个固定key值随后装包时变一下,随后编码中轮循来判断看是否有转变,有就提醒。

中小型发布订阅通告客户升级了 constringth 一样无

果真是康老师传统不清楚。

中小型发布订阅通告客户升级了 constringth 一样无

可是写完之后发觉太费劲了,必须手动式配备json文档,还要装包时改动,是否有更简单计划方案, 开展第二轮探讨。

第二轮探讨的方案是依据打过包以后产生的script src 的hash值来判断,每一次装包都是会形成唯一的hash值,只需轮循来判断不一样了,那一定是重新配置了.

中小型发布订阅通告客户升级了 constringth 一样无

3.代码编写

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('升级了')
})

4.检测

实行 npm run build 打个包

组装http-server

应用http-server 开一个服务项目

中小型发布订阅通告客户升级了 constringth 一样无

再次打个包npm run build

中小型发布订阅通告客户升级了 constringth 一样无

这样就能检测出是否有再次公布就能通告客户升级了。