Web ページを更新するようにユーザーに通知するための js 純粋なフロントエンド実装の再デプロイメント

需要: オンラインになった後、ユーザーが古いページに留まることがあります。ユーザーは Web ページが再デプロイされたことを知りません。ページにジャンプすると、JS 接続ハッシュが変更されてエラーが発生し、ユーザーは新しい機能です。最適化する必要があります。パッケージ化してリリースした後、顧客がシステムに入るたびに、システムの更新を求められ、顧客にメッセージが表示されます。

解決策: json ファイルをパブリックにアップロードし、パッケージ化されるたびに json を変更します。初めて ison データを取得して保存し、json データの時間が変更されるまでリクエストをポーリングし、プロンプトを出しました。ユーザー。

フロントエンドは、パッケージ化後に生成されたスクリプト src のハッシュ値に基づいて決定します。各パッケージは一意のハッシュ値を生成します。異なるかどうかを判断するためにポーリングされる限り、パッケージは再デプロイされている必要があります。
ここに画像の説明を挿入

ここに画像の説明を挿入
コードの実装: 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