前端项目部署,想要自动检测更新后通知用户刷新页面,但是发版后main.js入口文件不调用为什么?-灵析社区

卑微实习僧

在掘金看到的监测页面更新的方法,使用了new Worker,直接去请求页面获取etag、last-modified,判断和之前的是否相等,实测可用,定时器时间可以自定。 try { const worker = new Worker(new URL('./utils/autoUpdate.ts', import.meta.url), { type: 'module', }); worker.postMessage({ url: `${window.location.protocol}//${window.location.host}`, }); worker.onmessage = (e) => { if (e.data === 1) { ElMessageBox.alert('页面已更新,点击刷新页面', { confirmButtonText: '刷新', showClose: false, callback: (action: any) => { window.location.reload(); }, }); } }; worker.onerror = (err) => { console.error('->>>err', err); }; } catch (Err) { console.error('11111->>>err', Err); } utils/autoUpdate.ts export let previousTimeTag: string | null; // 时间戳,响应头中的tag和last-modified字段之一 let url: string; // 请求的url let intervalTimer: number; // 轮询的定时器 // 获取当前最新时间戳 async function getTimeTag() { const res = await fetch(url, { method: 'HEAD', cache: 'no-cache', }); return res.headers.get('etag') || res.headers.get('last-modified'); } // 判断Tag是否发生变化 async function juede() { const currentTimeTag: string | null = await getTimeTag(); console.log('currentTimeTag--> ' + currentTimeTag, ' ________ ' + 'previousTimeTag--> ' + previousTimeTag); if (currentTimeTag !== previousTimeTag) { intervalTimer && clearInterval(intervalTimer); self.postMessage(1); } } self.onmessage = function (e): void { const data = e.data; if ('url' in data) { try { url = data['url']; (async function () { // 通过立即执行函数,记录首次请求的时间戳,以便与后面轮询得出的时间戳进行对比 previousTimeTag = await getTimeTag(); intervalTimer && clearInterval(intervalTimer); // 执行轮询juede函数 intervalTimer = setInterval(juede, 60 * 1000 * 5); })(); } catch (err) { console.log('Worker got unknown message:111' + err); } } else { console.log('Worker got unknown message:' + data); } };

阅读量:1

点赞量:0

问AI