示例工程 22-security-service-worker

22-security-service-worker/04-service-worker/README.md

markdown · 1.2 KB

运行:22 · Service Worker 缓存

该示例需要 localStorage / IndexedDB / Service Worker,请用「新窗口打开」获得完整能力。

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

# 04 · Service Worker 缓存
 
**演示**:注册 `sw.js`,`install` 预缓存首页/脚本,`activate` 清旧缓存并 `clients.claim()`,`fetch` 走 cache-first;页面读取 `caches.keys()` 与缓存请求数。
**怎么看**:`node scripts/serve.mjs` 后打开 <http://localhost:8080/examples/22-security-service-worker/04-service-worker/>,开 Console。
**预期输出**:
 
```text
注册成功:scope=http://localhost:8080/examples/22-security-service-worker/04-service-worker/
当前页面是否被 SW 控制:true
fetch('./index.html') → 200(basic)
缓存空间:js-tutorial-v1
已缓存请求数:3
要点:cache-first 命中缓存直接返回,未命中再走网络;更新要管好版本。
```
 
**注意**:Service Worker 只在 `https:` 或 `http://localhost` 下可用,`file://` 与普通 IP 的 HTTP 都不行。首次注册时页面可能尚未被控制,`clients.claim()` 后才接管;示例等了 400ms。验证离线:DevTools → Application → Service Workers 勾选 Offline,刷新仍能打开(缓存命中)。更新 SW 时要改缓存名并清理旧缓存,否则旧资源会一直被命中。需 `http://localhost`。