[Whole Web] Auto check application website's updates

In a production environment, we want to prompt the user with a message when new scripts are available, asking

New scripts are available. Do you want to update?

The idea is straightforward: periodically (e.g., every minute, 10 seconds, depends on your cases), send a request to the server to check if there are any JavaScript updates. If updates are detected, it indicates functional changes.

At this point, we can display a toast notification informing the user to refresh the page to load the latest version.

 

Example code:

let lastSrcs; // last fetched sources

const scriptReg = /\<script.*src=["'](?<src>[^"']+)/gm;

async function extractNewScripts() {
    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 < lastSrcs.length; i++) {
        if (lastSrcs[i] !== newScripts[i]) {
            result = true;
            break;
        }
    }
    lastSrcs = newScripts;
    return result;
}

const DURATION = 1000 * 60 * 1; // 1 minutes
function autoRefresh() {
    setTimeout(async () => {
       const willUpdate = await needUpdate();
         if (willUpdate) {
              const result = confirm('New scripts are available. Do you want to update?');
              if (result) {
                  location.reload();
              }
         }
         autoRefresh();
    }, DURATION);
}

autoRefresh();

 

posted @   Zhentiw  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-09-15 [RxJS] Share data among multiple subscribers with Subjects
2022-09-15 [Typescript] 33. Medium - Flatten
2022-09-15 [Typescript] 32. Medium - Permutation
2022-09-15 [Algorithm] Permutations
2020-09-15 [CSS3] Use CSS Variables to Maintain the Aspect Ratio for an Element
2020-09-15 [GraphQL] Multi Query and Alias
2020-09-15 [Machine Learning] Gradient Checking
点击右上角即可分享
微信分享提示