vue 后台生产环境自动检测更新

typescript 复制代码
let lastSrcs: any; //上一次获取到的script地址

const scriptReg = /<script.*?type=['"]module['"].*?src=['"](.*?)['"].*?>/g;
/**
 * 获取最新页面中的script链接
 */
async function extractNewScript() {
    const env = import.meta.env.MODE
    if (env !== "production" ) return 
    const html = await fetch('/?_timestamp=' + Date.now()).then((res) => res.text());
    const result:any[] = [];
    // let match: any;
    scriptReg.lastIndex = 0
    const match = scriptReg.exec(html)
    if(match)result.push(match[1]);
    return result;
}
async function needUpdate() {
    const newScripts:any = await extractNewScript();
    if (!lastSrcs) {
        lastSrcs = newScripts;
        return false;
    }
    let result = false;
    if (lastSrcs.length !== newScripts.length) {
        result = true;
    }
    for (let i = 0; i < lastSrcs.length; i++) {
        if (lastSrcs[i] !== newScripts[i]) {
            result = true;
            break;
        }
    }
    lastSrcs = newScripts
    return result

}
const DURATION = 10000;
function autoRefresh() {
    setTimeout(async () => {
        const willUpdate = await needUpdate();
        if (willUpdate) {
            const result = confirm("页面有更新,点击确定刷新页面");
            if (result) {
                location.reload();
            }
        }
        autoRefresh();
    }, DURATION);
}
autoRefresh()

main.ts

import '@/utils/auto.update'

相关推荐
前端达人14 分钟前
都2026年了,还在用Options API?Vue组合式API才是你该掌握的“正确姿势“
前端·javascript·vue.js·前端框架·ecmascript
Dxy12393102161 小时前
Python检查JSON格式错误的多种方法
前端·python·json
chao-Cyril1 小时前
从入门到进阶:前端开发的成长之路与实战感悟
前端·javascript·vue.js
shalou29011 小时前
Spring 核心技术解析【纯干货版】- Ⅶ:Spring 切面编程模块 Spring-Instrument 模块精讲
前端·数据库·spring
大时光2 小时前
js 封装 动画效果
前端
大时光2 小时前
html翻页时钟 效果
前端
大猫子的技术日记2 小时前
2025 AI Agent 开发实战指南:从上下文工程到多智能体协作
前端·人工智能·bootstrap
前端达人2 小时前
被JavaScript忽视的Web Animations API:为什么说它是前端动画的真正未来?
开发语言·前端·javascript·ecmascript
忧郁的橙子.2 小时前
04-从零搭建本地AI对话系统:Ollama + DeepSeek-R1:7B + Streamlit
前端·chrome
PTC2 小时前
做了个 EPUB 阅读器,被「阅读进度同步」折磨了一周,总结 4 个血泪教训
前端