纯前端实现版本更新自动提示刷新

124 阅读1分钟

原理

每次版本更新后,重新打包,打包后的index.html中的js文件一定会变化,前端轮询对比上一次的文件,如果有区别就提示用户刷新页面更新

直接上代码,将以下代码引入到main.js就ok了

let lastSrcs;// 上一次获取到的script地址

const scriptReg = /\<script.*src=["'](?<src>[^"']+)/gm;// 匹配script中的src的正则
const DURATION = 1000 * 10;// 轮询间隔

// 获取最新页面中的script链接
async function extractNewScripts() {
    // 直接请求/就是能获取到index.html的内容,加上时间戳避免缓存
    const html = await fetch('/?timestamp=' + Date.now()).then(res => res.text());
    scriptReg.lastIndex = 0;// 重置正则下标
    let result = [];
    let match;
    while (match = scriptReg.exec(html)) {
        result.push(match.groups.src)
    }
    return result;
}

// 对比是否有更新
async function needUpdate() {
    const newScripts = await extractNewScripts();
    if (!lastSrcs) {
        lastSrcs = newScripts;
        return false;
    }
    let result = false;
    if (lastSrcs.length !== newScripts.length) {
        result = true;
    }
    for (let i = 0; i < newScripts.length; i++) {
        if (lastSrcs[i] !== newScripts[i]) {
            result = true;
            break;
        }
    }
    lastSrcs = newScripts;
    return result;
}

// 自动更新
function autoRefresh() {
    setTimeout(async () => {
        const willUpdate = await needUpdate();
        if (willUpdate) {
            const result = confirm('检测到新版本,点击确定将刷新页面并更新');
            if (result) {
                location.reload();
            }
        }
    }, DURATION)
}

autoRefresh();