离线缓存(PWA Service Worker)

真实难点:① SW 必须 HTTPS(localhost 例外);② 缓存策略选型:precache 壳 + runtime 缓存接口(stale-while-revalidate);③ 更新时要 skipWaiting + clients.claim 才生效;④ 缓存体积限制(50MB 左右)要设上限清理。
SW 未注册(本页为演示,需在真实站点部署 sw.js)

Service Worker 生命周期

1. register → 2. install 预缓存 app shell → 3. activate 清理旧缓存 → 4. fetch 拦截请求走缓存策略

缓存策略对比

Cache First:静态资源,快但更新滞后
Network First:接口数据,实时优先、失败兜底缓存
Stale-While-Revalidate:先返缓存、后台更新(最佳体验)