cache api只能在service worker或worklet线程中使用,页面主线程调用caches.open()会因上下文受限抛出securityerror或返回undefined;必须通过https(或localhost)注册service worker,且所有缓存操作需在install/fetch事件中配合event.waituntil()和request.clone()等规范写法执行。

Cache API 不能在 HTML 页面里直接用,必须通过 Service Worker 注册并控制 —— 写在 <script></script> 里调用 caches.open() 会报 SecurityError 或返回 undefined。
Service Worker 必须先注册成功,且脚本同源、HTTPS(或 localhost)
页面中注册代码类似:navigator.serviceWorker.register('/sw.js')。注意三点:
-
sw.js必须与页面同源,且响应头含Content-Type: text/javascript - 开发时若用
file://协议,Cache API 完全不可用;必须走http://localhost或 HTTPS - 注册后 Worker 不会立刻接管当前页面,需在
activate事件中加self.clients.claim()才能生效
install 事件中缓存静态资源,event.waitUntil() 不可省
常见错误是写完 caches.open().then(cache => cache.addAll([...])) 就结束,结果缓存没写进去。原因:
-
cache.addAll()是异步操作,不包在event.waitUntil()里,Worker 会认为install已完成,提前终止后续逻辑 - 列表中任一资源 404、跨域无 CORS、或非 GET 请求,整个
addAll()都会失败,缓存为空 - 路径必须用根相对路径,如
'/index.html',不能写'./index.html'或'index.html'
fetch 事件中分流请求,避免缓存污染
不是所有请求都该进缓存。关键看 request.destination:
使用 PptxGenJS 和 Python 解析,将结构化的 HTML/CSS 幻灯片内容转换为原生、可编辑的 PowerPoint(.pptx)演示文稿。
-
destination === 'document':HTML 文件,建议用Stale-While-Revalidate策略(先返回缓存,再 fetch 更新) -
destination === 'script'或'style':可直接cache.match(request)返回 -
destination === 'json'或'empty':跳过缓存,直连网络 - 务必加判断:
if (event.request.method !== 'GET') return fetch(event.request),否则 POST 请求可能意外匹配缓存
cache.match() 总是返回 undefined?检查 Request 是否被复用
这是最隐蔽也最高频的问题:一个 Request 对象只能被读取一次 body。典型错误写法:
const cached = await cache.match(request);<br>const fresh = await fetch(request); // ❌ 报错:Failed to execute 'fetch': Request has already been read
正确做法是 clone:
const cached = await cache.match(request);<br>const fresh = await fetch(request.clone()); // ✅
另外注意默认匹配严格:
- 带 query 参数的 URL(如
/logo.png?v=2)和不带参数的不会命中同一缓存项 - 需要宽松匹配时,传选项:
cache.match(request, { ignoreSearch: true, ignoreMethod: true }) - 确保缓存的是 status 200–299 的响应;304、404、500 不会被真正写入,但
cache.put()也不报错
Cache Storage 和 HTTP 缓存完全隔离,DevTools 的 Network 面板看不到 Cache API 缓存内容;要确认是否写入成功,必须打开 Application → Cache Storage 面板手动查看 —— 很多人卡在这一步,以为代码没生效,其实是没找对地方。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










