背景与价值直接使用 Cache API 进行离线缓存与精细化控制,搭配版本与失效策略提升稳定性。版本化缓存命名const STATIC_CACHE = 'static-v3';
const API_CACHE = 'api-v1';
安装与预缓存self.addEventListener('install', (event: ExtendableEvent) => {
event.waitUntil((async () => {
const cache = await caches.open(STATIC_CACHE);
await cache.addAll(['/index.html', '/styles.css', '/app.js']);
})());
});
激活与旧版本清理self.addEventListener('activate', (event: ExtendableEvent) => {
event.waitUntil((async () => {
const keys = await caches.keys();
await Promise.all(keys.filter(k => ![STATIC_CACHE, API_CACHE].includes(k)).map(k => caches.delete(k)));
await (self as any).clients.claim();
})());
});
路由与冲突解决self.addEventListener('fetch', (event: FetchEvent) => {
const url = new URL(event.request.url);
if (url.pathname.startsWith('/api/')) {
event.respondWith(networkFirst(event.request));
} else {
event.respondWith(cacheFirst(event.request));
}
});
async function cacheFirst(req: Request) {
const cache = await caches.open(STATIC_CACHE);
const hit = await cache.match(req);
if (hit) return hit;
const res = await fetch(req);
if (res.ok) cache.put(req, res.clone());
return res;
}
async function networkFirst(req: Request) {
const cache = await caches.open(API_CACHE);
try {
const res = await fetch(req);
if (res.ok) cache.put(req, res.clone());
return res;
} catch {
const hit = await cache.match(req);
if (hit) return hit;
return new Response('offline', { status: 503 });
}
}
指标验证(Chrome 128/Edge 130)静态命中率:≥ 90%;API 离线回退成功率 ≥ 97%。一致性:版本切换后错误内容率 ≤ 0.3%。稳定性:长驻 24h 无缓存膨胀与冲突失效问题。测试清单版本升级:旧缓存清理正确;离线路径仍可用。弱网场景:API 请求回退稳定,冲突解决正确。

发表评论 取消回复