前端页面自动检测更新解决方案 【version-polling】

前言

version-polling 是一个轻量级的 JavaScript 库,它可以实时检测 web 应用的 index.html 文件内容是否有变化。当服务端发布新版本后,前端会自动弹出更新提示,让用户刷新页面,以加载最新的资源和功能。这样可以提高用户体验和数据准确性。

GitCode - 全球开发者的开源社区,开源代码托管平台GitCode是面向全球开发者的开源社区,包括原创博客,开源代码托管,代码协作,项目管理等。与开发者社区互动,提升您的研发效率和质量。icon-default.png?t=O83Ahttps://gitcode.com/gh_mirrors/ve/version-polling/overview?utm_source=artical_gitcode&index=top&type=card&webUrl&isLogin=1

设计目的

为了解决后端部署之后,如何通知用户系统有新版本,并引导用户刷新页面以加载最新资源的问题。

1. 安装

npm install version-polling --save

2. 使用方式

  • 通过 npm 引入,并通过构建工具进行打包
// 在应用入口文件中使用: 如 main.js, app.jsx
import { createVersionPolling } from "version-polling";

createVersionPolling({
  appETagKey: "__APP_ETAG__",
  pollingInterval: 5 * 1000, // 单位为毫秒
  silent: process.env.NODE_ENV === "development", // 开发环境下不检测
  onUpdate: (self) => {
    // 当检测到有新版本时,执行的回调函数,可以在这里提示用户刷新页面
    const result = confirm("页面有更新,点击确定刷新页面!");
    if (result) {
      self.onRefresh();
    } else {
      self.onCancel();
    }
    // 强制更新可以用alert
    // alert('有新版本,请刷新页面');
  },
});
  • 通过 script 引入,直接插入到 HTML
<script src="//unpkg.com/version-polling/dist/version-polling.min.js"></script>

  <script>
    VersionPolling.createVersionPolling({
      appETagKey: "__APP_ETAG6__",  // 每次更新时,需修改,否则不会提示页面已更新
      pollingInterval: 5 * 1000,
      onUpdate: (self) => {
        // 当检测到有新版本时,执行的回调函数,可以在这里提示用户刷新页面
        if (self.options.htmlFileUrl.indexOf('http://localhost:9527') === -1) {
          const result = confirm("系统已更新,请刷新页面 (请在刷新前注意保存当前页面数据).");
          if (result) {
            self.onRefresh();
          } else {
            self.onCancel();
          }
        }
      },
    });
  </script>

3. 其余 可设置的api

参数

说明

类型

默认值

appETagKey

web 应用更新唯一标识字段名

string

__APP_ETAG__

pollingInterval

轮询间隔,单位为毫秒,默认为 5 分钟

number

5 * 60 * 1000

htmlFileUrl

web 应用网站运行目录

string

${location.origin}${location.pathname}

silent

安静模式,为true时,不会进行实时监测

boolean

false

silentPollingInterval

安静模式,为true时,不做轮询任务

boolean

false

silentPageVisibility

安静模式,为true时,不做页面可见状态监听

boolean

false

forceUpdate

强制更新,为true时,取消也会检查更新

boolean

false

onUpdate

更新检测的回调函数,可以自定义更新的逻辑

(self) => void

-

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小牛学前端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值