【问题标题】:API cache in PWA generated by Create React App v4Create React App v4 生成的 PWA 中的 API 缓存
【发布时间】:2021-08-18 07:04:06
【问题描述】:

This 是使用cra-template-pwa-typescript 的模板。如何缓存外部 API 和图像?

【问题讨论】:

    标签: reactjs create-react-app progressive-web-apps


    【解决方案1】:

    c-r-a v4 使用一个模型,在该模型中,您可以完全控制由 Workbox 提供支持的 Service Worker 文件。

    Workbox 文档中有关缓存的一般指导应该会有所帮助:https://developers.google.com/web/tools/workbox/guides/handle-third-party-requests

    举一个具体的例子,假设您想使用 stale-while-revalidate 策略缓存所有跨域图像。您可以通过将此路由添加到您的服务工作人员文件来做到这一点:

    registerRoute(
      ({request, url}) => url.origin !== self.location.origin &&
                          request.destination === 'image',
    
      new StaleWhileRevalidate({
        cacheName: 'cross-origin-images',
        plugins: [
          // Ensure that once this runtime cache reaches a maximum size the
          // least-recently used images are removed.
          new ExpirationPlugin({ maxEntries: 50 }),
        ],
      })
    );
    

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 1970-01-01
      • 2021-10-31
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多