前端升级客户端自动更新
生活随笔
收集整理的這篇文章主要介紹了
前端升级客户端自动更新
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
SPA類型應用,前端熱發布后,用戶端由于瀏覽器緩存不會重新獲取index.html 導致用戶沒有及時看到最新版本
所以寫了一個插件用戶協助客戶端實時更新
//思路:對比每一個script中的src的地址有無變化 因為打包后的js名稱一般為 test.dawe13s5.js 中間8位為哈希值 每次打包均不一樣·
//將此文件導入main.js 即可
let lastSrcs //上一次的所有script地址
const scriptReg = new RegExp('<script\\b[^<]*\\bsrc\\s*=\\s*["\']([^"\']*)["\'][^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>', 'gi');
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) { //script個數不一樣 肯定有更新
result = true
}
for (let i = 0; i < lastSrcs.length; i++) { // 個數一樣就一個個對比名稱
if (lastSrcs[i] !== newScripts[i]) {
result = true
break
}
}
lastSrcs = newScripts
return result
}
const DURATION = 2000
function autoRefresh() {
setTimeout(async () => {
const willUpdate = await needUpdate()
if (willUpdate) {
const result = confirm('頁面有更新,點擊確定更新頁面')
if (result ) {
// location.reload() // == F5
location.href = location.href + '?timestamp=' + new Date().now(); //刪除緩存重新加載 == Ctrl + F5
}
}
autoRefresh()
},DURATION)
}
autoRefresh()
總結
以上是生活随笔為你收集整理的前端升级客户端自动更新的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Markdown & typora 速查
- 下一篇: AtCoder Beginner Con