vue实现打包前端代码部署到服务器之后提示用户刷新界面

class Updater {
    oldScript:any = [];
    newScript:any = []; 
    dispatch:any = {};
 
    constructor() {
        this.oldScript = [];
        this.newScript = [];
        this.dispatch = {};
        if(import.meta.env.MODE != 'development'){
            this.init(); // 初始化
            this.timing();
        }
    }
 
    async init() {
        const html = await this.getHtml();
        this.oldScript = this.parserScript(html);
    };
 
    async getHtml() {
        const html = await fetch('/?t='+new Date().getTime()).then(res => res.text());
        return html
    };
 
    parserScript(html:any) {
        const reg = new RegExp(/<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/ig)
        return html.match(reg)
    }
 

    on(key:any, fn:any) {
        (this.dispatch[key] || (this.dispatch[key] = [])).push(fn)
        return this;
    }
 
    compare(oldArr:any, newArr:any) {
        const base = oldArr.length;
        const arr = Array.from(new Set(oldArr.concat(newArr)));
        if (arr.length === base) {
            // this.dispatch['no-update'].forEach(fn => {
            //     fn();
            // })
        } else {
            this.dispatch['update'].forEach((fn:any) => {
                fn();
            })
        }
    };
 
    async timing() {
        setInterval(async () => {
            const newHtml = await this.getHtml();
            this.newScript = this.parserScript(newHtml);
            this.compare(this.oldScript, this.newScript)
        }, 10 * 1000);
    };
}
 
export default Updater;

使用:

import Updater from '@/utils/checkedUpDate.ts'
const AutoUpdate = new Updater()
AutoUpdate.on('update',()=>{
  setTimeout(async()=>{
      const result = confirm('当前网站有更新,请点击确定刷新页面体验');
      if(result){
        location.reload();
      }
  },500)
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值