사용자에게 웹 페이지를 새로 고치도록 알리는 Node.js 순수 프런트 엔드 구현 재배포

요구 사항: 사용자가 온라인에 접속한 후 이전 페이지에 머무는 경우가 있습니다. 사용자는 웹 페이지가 다시 배포되었음을 알지 못합니다. 페이지로 이동할 때 때때로 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)
    }
}

그리고 뭐? —가장 바깥쪽 앱 파일에서 이 ts 파일을 참조합니다.

Vue 프로젝트인 경우 onMoutend 후크 함수에 넣습니다.

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

여기에 이미지 설명을 삽입하세요.

반응 프로젝트인 경우, componentDidMount()
에 배치할 수 있습니다.

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

여기에 이미지 설명을 삽입하세요.
여기에 이미지 설명을 삽입하세요.

즉, 업데이트 메시지가 표시되었지만 고객이 업데이트를 클릭하지 않은 경우 일정 시간이 지나면 페이지에서 팝업 메시지가 전송되는 등 가능한 문제에 주의하세요. 이때 타이머를 지워야 한다는 점을 기억해야 합니다. 클리어간격().
즉, 폴링할 때 변수를 할당합니다.

 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