实现一个检测前端是否有资源更新的方法

开发环境是vite+vue,利用hashValue检测,直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import axios from 'axios'
var match;
var srcArray = [];
var checkTaskInterval = null
const getNewVersionHash = async () => {
srcArray = []
const pageUrl = `${window.location.protocol}//${window.location.host}/index.html?v=${new Date().getTime()}`
const response = await axios.get(pageUrl)
let htmlStr = response.data
var regex = /<script[^>]*src=['"]([^'"]*)['"][^>]*>/gi;
while (match = regex.exec(htmlStr)) {
srcArray.push(match[1]); // 将每个src的值添加到数组中
}
}
const checkVersion = async () => {
srcArray = []
await getNewVersionHash()
console.log(srcArray)
if(!localStorage.getItem('jsHashVersion')){
localStorage.setItem('jsHashVersion',JSON.stringify(srcArray))
return
}
if(localStorage.getItem('jsHashVersion') && localStorage.getItem('jsHashVersion') !== JSON.stringify(srcArray)){
localStorage.setItem('jsHashVersion',JSON.stringify(srcArray))
clearInterval(checkTaskInterval)
alert('当前页面存在新版本,点击确定后更新使用')
window.location.reload(false)
}
}
const runCheckTask = async () => {
checkTaskInterval = setInterval(() => {
checkVersion()
},1000)
}


runCheckTask()

实现一个检测前端是否有资源更新的方法
https://blog.funfe.cn/2024/06/18/20240618145954/
作者
李鹏杰
发布于
2024年6月18日
许可协议