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

半寸时光爱思考

想实现,"前端项目部署自动检测更新后通知用户刷新页面".但是发版后,main.js入口文件并不再次执行是为什么? 在main.js引入了version版本比较,但是发版之后,浏览器页面并不会自动再次执行main.js,导致用户如果之前一直在老页面,即便我发版,他也更新不到. 我是用oss发版的,文件名字hash我也做了处理,但是为什么引用文件名字都变了,浏览器还是老页面吗呢,不去读最新的资源文件![这是老页面 引用的js文件](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241015/0af29bb8c4b50a259ffdd37ef520c4fe.png)![这是新页面加了hash的文件名](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241015/377ac5c8fc571b8a6617ac2f9fc2ee41.png) 但是项目页面如果不刷新(下图是老页面读的),一直停留在老页面,他就一直访问老页面js,导致我的版本更新代码他读不到 ![项目老页面引用的](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241015/ad5cb9e13525eebcf362d7e4c08b66fb.png) 这种我要怎么处理

阅读量:13

点赞量:0

问AI
在掘金看到的监测页面更新的方法,使用了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); } };