前端与浏览器 / 进阶

Service Worker 离线缓存:先设计更新,再设计命中

介绍 Service Worker 生命周期、预缓存与运行时缓存策略,并处理版本升级、缓存清理和失败回退。

按请求类型选择策略

应用壳和带哈希静态资源适合 Cache First;新闻、库存等时效数据适合 Network First,并设置超时和缓存回退;头像等非关键资源可用 Stale While Revalidate。 不要缓存所有 GET 请求。接口错误响应、范围请求和包含用户隐私的响应都需要明确规则。

EXAMPLE / 01Service Worker
self.addEventListener('activate', event => {
  event.waitUntil((async () => {
    const names = await caches.keys();
    await Promise.all(names
      .filter(name => name.startsWith('static-') && name !== STATIC_CACHE)
      .map(name => caches.delete(name)));
    await self.clients.claim();
  })());
});

把实现拆成可验证的小块

版本升级必须包含旧缓存清理

最后回到真实页面检查

更新流程要避免页面与资源版本错配