【问题标题】:Service Worker: How to cache images that do not have extensions using WorkboxService Worker:如何使用 Workbox 缓存没有扩展的图像
【发布时间】:2019-04-17 11:25:38
【问题描述】:

我是我的页面中的服务人员的新手,我有没有扩展名的图像 [*.jpg、*.png 等],比如我从 API 获取的“www.domain.com/api/media/a2b93f21-1acf-4e5e-9b19-6d7c68aaadc2”。

以下代码可以正常工作,但不适用于此类图像

workbox.routing.registerRoute(
    // Cache image files.
    /\.(?:png|jpg|jpeg|svg|gif)$/,
    // Use the cache if it's available.
    new workbox.strategies.CacheFirst({
        // Use a custom cache name.
        cacheName: 'image-cache',
        plugins: [
            new workbox.expiration.Plugin({
                // Cache only 20 images.
                maxEntries: 20,
                // Cache for a maximum of a week.
                maxAgeSeconds: 7 * 24 * 60 * 60,
            })
        ],
    })
);

有什么建议吗?

【问题讨论】:

  • 您不能调整您的路由规则以应用于/api/media/ 目录中的任何内容吗?除了图片之外,您还提供其他服务吗?
  • 其实有文件管理器可以上传图片,也可以通过API调用media获取图片,前面我们只是得到一个Guid作为文件名。
  • 解决此问题的一种方法是检查所请求文件的标题。如果 headers 告诉 SW 请求的实体是图像文件,则缓存它。

标签: javascript service-worker workbox image-caching


【解决方案1】:

带有工作箱,来自manual -

你可以使用RequestDestination枚举类型 确定策略的请求的目的地。例如,当 目标是数据

workbox.routing.registerRoute(
  // Custom `matchCallback` function
  ({event}) => event.request.destination === 'image',
  new workbox.strategies.CacheFirst({
    cacheName: 'image',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 20,
        maxAgeSeconds: 7 * 24 * 60 * 60, // 1 week
      }),
    ],
  })
);

在普通的服务工作者中,您可以查看request accept header

if (request.headers.get('Accept').indexOf('image') !== -1) { 
    ... stash in cache ...
} 

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-05-31
  • 2018-12-24
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 1970-01-01
  • 2016-10-28
  • 1970-01-01
相关资源
最近更新 更多