前端部署后自动检测更新

每当前端部署到服务器后,用户如果不刷新页面总会遇到点击卡住或者点不动的问题,相信很多搞前端的同学都会遇到这种情况,本人也遇到过很多次这种情况,于是就想了个办法,让项目在线上自动检测版本更新,话不多说直接上代码:

第一种办法:定时请求版本文件与本地版本标识对比,如果不想等就自动刷新页面

  1. 在打包工具中每次打包自动写入一个版本文件(我这里用的是vite)
javascript 复制代码
 writeBundle() {
      const timestamp = new Date().toLocaleString() + Math.random().toString(36).substring(2, 7)
      fs.writeFileSync('dist/build-timestamp.txt', timestamp)
      console.log('✅ dist/build-timestamp.txt 写入成功,用于部署后检测更新')
    },
  1. 新建checkVersion.ts文件,定时请求这个文件,如果本地没有版本就自动存到本地
javascript 复制代码
let versionUpdateTimer: number | null = null
let pollingActive = false

async function fetchVersionAndUpdate() {
  try {
    const oldTimestamp = localStorage.getItem('build-timestamp')
    const res = await fetch('/build-timestamp.txt', { cache: 'no-cache' })

    if (!res.ok) {
      throw new Error(`HTTP error! status: ${res.status}`)
    }

    const newTimestamp = await res.text()
    console.log('当前版本时间戳:', newTimestamp)

    if (!oldTimestamp) {
      localStorage.setItem('build-timestamp', newTimestamp)
    }

    if (oldTimestamp !== newTimestamp) {
      localStorage.setItem('build-timestamp', newTimestamp)
      window.location.reload()
    }

    // 请求完成且版本没变,延迟10秒后继续轮询(仅当轮询状态激活时)
    if (pollingActive) {
      versionUpdateTimer = window.setTimeout(fetchVersionAndUpdate, 10 * 1000)
    }
  }
  catch (err) {
    console.error('获取版本失败:', err)
    // 请求失败时延迟15秒重试
    if (pollingActive) {
      versionUpdateTimer = window.setTimeout(fetchVersionAndUpdate, 15 * 1000)
    }
  }
}

function startPolling() {
  if (!pollingActive) {
    pollingActive = true
    console.log('轮询开始')
    fetchVersionAndUpdate() // 立即执行一次
  }
}

function stopPolling() {
  pollingActive = false
  if (versionUpdateTimer !== null) {
    clearTimeout(versionUpdateTimer)
    versionUpdateTimer = null
    console.log('轮询停止')
  }
}

// 根据页面当前状态决定是否开启轮询
if (document.visibilityState === 'visible' && location.hostname !== 'localhost') {
  startPolling()
}

// 监听页面显示/隐藏,动态开启/关闭轮询
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'visible' && location.hostname !== 'localhost') {
    startPolling()
  }
  else {
    stopPolling()
  }
})
  1. 入口文件中导入 checkVersion.ts 文件(如果是vue就是main.ts中)
javascript 复制代码
import '@/utils/checkVersion'

至此就大功告成了,亲测可用哦,相信一定不止这一个方法可以实现,有想法的小伙伴欢迎一起来讨论

相关推荐
知了学历孙老师5 小时前
小自考的校考和统考,出题方和难度差在哪
java·大数据·前端
ShineWinsu7 小时前
对于JavaScript:操作元素的解析
开发语言·前端·javascript·面试·web·dom·元素
福兮说8 小时前
JSON 格式正确,数据就可靠吗?我用一份自编配置检查类型与空值
java·前端·json
程序员老赵9 小时前
Docker 部署青龙面板:轻松搭建定时任务管理平台
前端·docker·开源
Swot9 小时前
Asciidoctor 公式数字下标错位问题:原因分析与解决方案
前端
Swot9 小时前
leo-editor 中将 Markdown 内容转成 asciidoc 格式
前端
狒狒AI10 小时前
Remotion / GSAP+Three / HyperFrames / Skia 四栈实测:代码渲染知识视频的选栈方法(附开源技能)
前端·人工智能·aigc
修炼的dance10 小时前
浏览器里导出H.265,8.5秒和55.5秒差在硬件
前端
补码缩写10 小时前
WebCodecs选编码器,探测之后还要验解码和播放
前端
大文说跨境10 小时前
亚马逊多账号管理浏览器怎么选?云登/紫鸟/AdsPower 对比
java·前端·自动化