Hacker News 中文摘要

RSS订阅

缓存 -- Cache

文章摘要

MDN文档介绍了Cache接口的实例方法,包括match()用于返回匹配请求的响应,matchAll()返回所有匹配响应的数组,add()addAll()分别用于添加单个或多个URL的响应到缓存,put()则直接将请求和响应添加到缓存中。这些方法帮助开发者管理缓存资源,提升应用性能。

文章总结

Cache - Web APIs | MDN

主要内容:

本文介绍了 Cache 接口的实例方法及其使用场景。Cache 接口是 Service Worker API 的一部分,用于缓存网络请求的响应,以便在离线或网络不佳时提供快速访问。

实例方法:

  1. Cache.match():返回一个 Promise,解析为 Cache 对象中第一个匹配请求的响应。
  2. Cache.matchAll():返回一个 Promise,解析为 Cache 对象中所有匹配请求的响应数组。
  3. Cache.add():获取指定 URL 的响应并将其添加到缓存中,功能上等同于先调用 fetch(),再使用 put() 将结果存入缓存。
  4. Cache.addAll():获取一组 URL 的响应并将它们添加到缓存中。
  5. Cache.put():将请求及其响应添加到缓存中。
  6. Cache.delete():查找并删除与请求匹配的缓存条目,返回一个 Promise,解析为 true 表示删除成功,false 表示未找到匹配条目。
  7. Cache.keys():返回一个 Promise,解析为 Cache 对象中所有键的数组。

示例代码:

以下代码片段展示了如何在 Service Worker 中使用 Cache 接口进行选择性缓存。代码首先检查缓存中是否存在匹配的字体资源,如果存在则直接返回,否则从网络获取资源并将其缓存。代码还处理了 fetch() 操作中的异常,并展示了缓存版本管理的最佳实践。

``javascript const CACHE_VERSION = 1; const CURRENT_CACHES = { font:font-cache-v${CACHE_VERSION}`, };

self.addEventListener("activate", (event) => { // 删除不在 CURRENTCACHES 中的缓存 const expectedCacheNamesSet = new Set(Object.values(CURRENTCACHES)); event.waitUntil( caches.keys().then((cacheNames) => Promise.all( cacheNames.map((cacheName) => { if (!expectedCacheNamesSet.has(cacheName)) { console.log("Deleting out of date cache:", cacheName); return caches.delete(cacheName); } return undefined; }), ), ), ); });

self.addEventListener("fetch", (event) => { console.log("Handling fetch event for", event.request.url);

event.respondWith( caches .open(CURRENT_CACHES.font) .then((cache) => cache.match(event.request)) .then((response) => { if (response) { console.log(" Found response in cache:", response); return response; }

    console.log(" No response for %s found in cache. About to fetch from network…", event.request.url);

    return fetch(event.request.clone()).then((response) => {
      console.log("  Response for %s from network is: %O", event.request.url, response);

      if (response.status < 400 && response.headers.has("content-type") && response.headers.get("content-type").match(/^font\//i)) {
        console.log("  Caching the response to", event.request.url);
        cache.put(event.request, response.clone());
      } else {
        console.log("  Not caching the response to", event.request.url);
      }

      return response;
    });
  })
  .catch((error) => {
    console.error("  Error in fetch handler:", error);
    throw error;
  }),

); }); ```

Cookies 和 Cache 对象:

Fetch API 在返回 Response 对象之前会剥离 Set-Cookie 头信息,因此存储在 Cache 中的 Response 不会包含 Set-Cookie 头信息,也不会导致任何 cookie 被存储。

规范:

Cache 接口的规范详见 Service Workers # cache-interface

浏览器兼容性:

加载中…

相关链接:

帮助改进 MDN:

本文是否对您有帮助?
是 否

了解如何贡献
本文最后修改于 2025 年 5 月 23 日,由 MDN 贡献者 编辑。

评论总结

评论内容主要围绕Cache API的使用场景、优缺点以及相关技术建议展开,观点较为多样,既有对其功能的肯定,也有对其局限性的讨论。

  1. Cache API的实用性

    • 支持者认为Cache API在构建离线Web应用方面非常有用,尤其是与服务工作者(Service Worker)结合时。
    • 引用:
      • "Cache is super useful for making web apps available offline."(Cache API在使Web应用离线可用方面非常有用。)
      • "With the right caching strategies you can make a really effective offline web app."(通过正确的缓存策略,可以构建非常高效的离线Web应用。)
  2. 与传统HTTP缓存的对比

    • 有评论指出Cache API与传统HTTP缓存是分离的,前者提供了更直接的控制,但无法直接访问HTTP缓存。
    • 引用:
      • "The Cache API is separate from the traditional HTTP cache."(Cache API与传统HTTP缓存是分离的。)
      • "You can access the HTTP cache indirectly by fetching with appropriate HTTP headers."(可以通过适当的HTTP标头间接访问HTTP缓存。)
  3. Cache API的局限性

    • 部分评论认为,如果没有服务工作者,Cache API的功能有限,且在某些场景下,传统缓存方法可能更简单有效。
    • 引用:
      • "Absent a service worker this API won't give you a whole lot."(如果没有服务工作者,这个API的功能有限。)
      • "What I wanted could be achieved by combining plain old cache headers with some more intelligent cache busting query strings."(我需要的功能可以通过结合传统缓存标头和更智能的缓存清除查询字符串来实现。)
  4. 技术建议与工具推荐

    • 评论中提到了使用Serwist和Workbox等工具来优化服务工作者和缓存策略,并建议开发者学习不同的缓存策略。
    • 引用:
      • "Use Serwist, don’t learn Workbox."(使用Serwist,不要学Workbox。)
      • "Learn all the different caching strategies."(学习所有不同的缓存策略。)

总结:Cache API在离线Web应用开发中具有显著优势,但其功能依赖于服务工作者,且与传统HTTP缓存存在差异。开发者应根据具体需求选择合适的缓存策略和工具,如Serwist或Workbox,以优化应用性能。