1.0.4 • Published 2 years ago
updatewx1 v1.0.4
使用介绍
1.很多时候一些系统发布了新版本,但是因为之前的用户已经登录了正在使用中,就不会主动的去刷新版本,导致新功能滞后于用户使用,体验很不好。
2.解决这个问题有很多办法,一种就是将用户的token过期时间调整,用户因为登录过期去重新登录的时候页面跳转引起资源重新加载,一种是在打包文件里面放一个json文件,每次上线的时候去修改json文件的值,如果发生了变化,提醒一下用户可以开始刷新页面了。一种是后端与前端通过websocket的方式建立链接后端检测资源的变化,每一次部署完之后后端告知前端。
3.因为希望不借助后端去实现,所以本文采用的方法其实跟书写json的方式很像,但是比手动修改json要稍微的方便点。每次打包的时候js的哈希值会变。根目录html引入的js文件前缀会变,我们检测这个前缀的变化就知道资源是不是发生了变化,本插件用的就是这样的方式。
使用方法
import {Update} from "./update.js";
console.log(Update)
const up=new Update({
timer:2000,
url:"../dist/app.html"
})
up.on('no-update',()=>{
console.log('weigegxin')
})
up.on('update',()=>{
console.log('更新了')
})
export class Update {
oldScript
newScript
dispatch
timeid
pathurl
constructor(data){
this.oldScript='';
this.newScript='';
this.pathurl=data.url;
this.dispatch={};
this.timeid=null;
this.init();
this.timing(data.timer);
}
async init(){
const html=await this.getHtml();
this.oldScript=this.parseScript(html)
}
async getHtml(){
const html=await fetch(this.pathurl).then(res=>res.text());
return html;
}
parseScript(html){
const reg = new RegExp(/<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/ig) //script正则
return html.match(reg); //匹配script标签
}
// 发布订阅通知 key:'no-update' | 'update' fn:Function
on(key,fn){
(this.dispatch[key] || (this.dispatch[key]=[])).push(fn);
return this;
}
compare(oldArr,newArr){
// 如果新旧length一样没有更新
if(oldArr==newArr){
this.dispatch['no-update'].forEach(fn=>{
fn();
})
}else{
// 否则通知更新
this.oldScript=this.newScript;
this.dispatch['update'].forEach(fn=>{
fn();
})
}
}
clearAll(){
clearInterval(this.timeid);
}
// 我知道了
ignore(){
this.oldScript=this.newScript;
}
// 前往刷新
fresh(){
window.reload();
}
timing(time){
this.timeid=setInterval(async ()=>{
const newHtml = await this.getHtml();
this.newScript=this.parseScript(newHtml);
this.compare(this.oldScript,this.newScript);
},time)
}
}