1.html文件
// html顶部head 添加 禁用缓存
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
2.main,js引入
import '@/utils/version.js'
3.js
/*
* @Description: gaobo
* @Date: 2021-03-25 15:41:51
* @FilePath: \src\utils\version.js
*/
import axios from 'axios'
(function (doc, win) {
// 定时器五分钟轮询一次,timerVersion 是全局变量,默认值为 null
setInterval(getHash, 300000)
async function getHash () {
// 本地环境可以不触发
if (process.env.VUE_APP_TITLE != 'development') {
// 当前版本的 hash
const curScript = document.getElementsByTagName('script')
let curHashSrc = ''
for(const key in curScript) {
// 获取本地 带hash值的 app.***js 文件
if (curScript[key].src && curScript[key].src.indexOf('app') != -1) {
curHashSrc = curScript[key].src
}
}
// 在 js 中请求首页地址不会更新页面
const response = await axios.get(`${window.location.protocol}//${window.location.host}/?_t=${new Date().getTime()}`)
// 返回的是字符串,需要转换为 html
const el = document.createElement('html')
el.innerHTML = response.data
if (el.getElementsByTagName('script') && el.getElementsByTagName('script').length) {
const newScript = el.getElementsByTagName('script')
let newHashSrc = ''
for(const key in newScript) {
// 获取服务器 带hash值的 app.***js 文件
if (newScript[key].src && newScript[key].src.indexOf('app') != -1) {
newHashSrc = newScript[key].src
}
}
// 如果服务器和本地app.***js文件hash值不一致 这刷新页面
if (curHashSrc && newHashSrc && curHashSrc !== newHashSrc) {
window.location.reload()
}
}
}
}
})(document, window)
4.webpack 构建脚本 采用hash值
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[hash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},