首页 > 其他分享 >[Whole Web] Auto check application website's updates

[Whole Web] Auto check application website's updates

时间:2024-09-15 20:24:20浏览次数:8  
标签:website Web const Auto let result newScripts lastSrcs 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();

 

标签:website,Web,const,Auto,let,result,newScripts,lastSrcs,updates
From: https://www.cnblogs.com/Answer1215/p/18415587

相关文章