前言
version-polling 是一个轻量级的 JavaScript 库,它可以实时检测 web 应用的 index.html 文件内容是否有变化。当服务端发布新版本后,前端会自动弹出更新提示,让用户刷新页面,以加载最新的资源和功能。这样可以提高用户体验和数据准确性。
设计目的
为了解决后端部署之后,如何通知用户系统有新版本,并引导用户刷新页面以加载最新资源的问题。
1. 安装
npm install version-polling --save
2. 在 index.html 中添加如下代码
<script src="//unpkg.com/version-polling/dist/version-polling.min.js"></script>
<script>
VersionPolling.createVersionPolling({
appETagKey: "__APP_ETAG3__", // 每次更新时,需修改,否则不会提示页面已更新
pollingInterval: 5 * 1000,
onUpdate: (self) => {
// 判断当前是否为本地环境
if (self.options.htmlFileUrl != 'http://localhost:8089/') {
// 当检测到有新版本时,执行的回调函数,可以在这里提示用户刷新页面
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 | - |