场景重现
客户:昨天让你修复的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的变化用来判断是否更新