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

当前使用版本为Vue2.5.2,需要实现一个简单的发布订阅模式;

文件路径:src-->until-->AutoUpdate.js

AutoUpdate.js

 
/**
 * 前端重新部署通知用户刷新网页
 */
 
class Updater {
    oldScript = []; // 存储第一次值也就是script 的hash 信息
    newScript = []; // 获取新的值 也就是新的script 的hash信息
    dispatch = {}; // 小型发布订阅通知用户更新了
 
    constructor() {
        this.oldScript = [];
        this.newScript = [];
        this.dispatch = {};
        this.init(); // 初始化
        this.timing();
    }
 
    async init() {
        const html = await this.getHtml();
        this.oldScript = this.parserScript(html);
    };
 
    async getHtml() {
        const html = await fetch('/').then(res => res.text());//读取index html
        return html
    };
 
    parserScript(html) {
        const reg = new RegExp(/<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/ig) //script正则
        return html.match(reg) //匹配script标签
    }
 
    //发布订阅通知
    on(key, fn) {
        (this.dispatch[key] || (this.dispatch[key] = [])).push(fn)
        return this;
    }
 
    compare(oldArr, newArr) {
        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();
            })
        }
    };
 
    async timing() {
        setInterval(async () => {
            const newHtml = await this.getHtml();
            this.newScript = this.parserScript(newHtml);
            this.compare(this.oldScript, this.newScript)
            //这边给的是默认值15000,也可以自定义秒数
        }, 15000);
    };
}
 
export default Updater;

main.js文件中引入并使用即可

import Vue from 'vue'
 
import Updater from "./utils/AutoUpdate.js";
 
//前端重新部署通知用户刷新网页
const AutoUpdate = new Updater()
AutoUpdate.on('update',()=>{
  setTimeout(async()=>{
      const result = confirm('当前网站有更新,请点击确定刷新页面体验');
      if(result){
        location.reload();
      }
  },500)
})
 
 
new Vue({
  el: '#app',
  render: h => h(App)
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值