前端项目更新自动通知用户刷新页面

文章介绍了一种通过创建update.js插件来自动检测HTML中script标签内JS变化的方法,当有更新时,通知用户刷新页面。该插件使用定时任务检查新版本,并通过比较旧版和新版脚本来判断是否有更新。
摘要由CSDN通过智能技术生成

场景重现

客户:昨天让你修复的BUG怎么还没修复?
猿人:早都更新了

客户:我这还是不好使啊
猿人:【ctrl】+【f5】强制刷新一下

客户:你说啥?我听不懂。

猿人:......

针对上述问题我们此次找到了解决方案

1、创建update.js插件
export class Updater {
    constructor(options) {
      this.oldScript = [];
      this.newScript = [];
      this.dispatch = {};
      this.interVal=null;
      this.init();
      this.timing(options.timer || 2000);
    }
  
    async init() {
      const html = await this.getHtml();
      this.oldScript = this.parserScript(html);
    }
  
    async getHtml() {
      const html = await fetch("/").then((res) => res.text());
      return html;
    }
  
    parserScript(html) {
      const reg = new RegExp(/<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/gi);
      return html.match(reg);
    }
  
    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)));
      if (arr.length === base) {
        this.dispatch["no-update"].forEach((fn) => {
          // 没有更新
          fn();
        });
      } else {
        this.dispatch["update"].forEach((fn) => {
          // 有新版本更新
          fn();
        });
      }
    }
  
    // 开启定时查询
    timing(time) {
      this.interVal=setInterval(async () => {
        const newHtml = await this.getHtml();
        this.newScript = this.parserScript(newHtml);
        this.compare(this.oldScript, this.newScript);
      }, time);
    }

    // 关闭定时器
    closeInval(){
      if (this.interVal) {
        clearInterval(this.interVal); 
      }
    }
  }
2、在需要引入的地方引入这个插件

ps:一般是在App.vue或者Layout.vue下引入 用来提示用户

import {Updater} from '@/utils/update';

使用方法


      // 未更新通知
      const up = new Updater({
        timer: 2000
      })
      up.on('no-update', () => {
        console.log('未更新');
      });
      // 更新通知
      up.on('update', () => {
        alert('大佬们,有版本更新,需要刷新页面了')
      });
    },

到此便结束了

3、说明

这中方法是监听打包后的html中script中引用的js的变化用来判断是否更新

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值