Appearance
前端版本轮询工具,用于定期检测线上资源是否发生更新,并在发现新版本时触发通知。
安装
bash
pnpm add @mingto/version-polling快速开始
typescript
import { createVersionPolling } from '@mingto/version-polling'
const polling = createVersionPolling({
pollingInterval: 60,
fileUrl: '/manifest.json',
})
polling.on('update', () => {
window.location.reload()
})也可以直接使用类:
typescript
import { VersionPolling } from '@mingto/version-polling'
const polling = new VersionPolling({
pollingInterval: 60,
fileUrl: '/',
})API
createVersionPolling(options)
创建版本轮询实例。
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
pollingInterval | number | 60 | 轮询间隔,单位秒 |
fileUrl | string | window.location.pathname | 要检测的文件地址,支持 HTML 路由或 JSON 文件 |
typescript
const polling = createVersionPolling({
pollingInterval: 30,
fileUrl: '/manifest.json',
})on(eventName, callback)
监听轮询事件,返回当前实例,支持链式调用。
| 事件名 | 回调参数 | 说明 |
|---|---|---|
update | - | 检测到版本更新时触发 |
typescript
polling.on('update', () => {
console.log('检测到新版本')
})检测模式
工具会根据 fileUrl 的后缀自动选择检测模式:
| 文件类型 | 检测模式 | 说明 |
|---|---|---|
.json | version | 读取 JSON 中的 version 字段,并使用语义化版本比较 |
| 其它地址 | identifier | 使用响应头中的 ETag 或 Last-Modified 判断资源是否变化 |
JSON 版本检测示例
目标文件内容示例:
json
{
"version": "1.0.1"
}当远端版本号大于首次记录的版本号时,会触发 update 事件。
HTML 或其它资源检测示例
typescript
createVersionPolling({
fileUrl: '/',
pollingInterval: 60,
}).on('update', () => {
location.reload()
})这类地址会通过 HEAD 请求读取 ETag 或 Last-Modified,当标识变化时触发 update。
页面可见性处理
实例创建后会监听 visibilitychange:
- 页面不可见时暂停轮询
- 页面重新可见时恢复轮询
- 检测到更新后会停止轮询并清理 Worker 与事件监听