javascript - 服务人员 : How to cache images that do not have extensions using Workbox

标签 javascript service-worker workbox image-caching

我是 Service Worker 的新手,在我的页面中,我有没有扩展名的图像[*.jpg、*.png 等],如下所示“www.domain.com/api/media/a2b93f21-1acf-4e5e-9b19-6d7c68aaadc2”,我从 API 获取它们。

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

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,
            })
        ],
    })
);

有什么建议吗?

最佳答案

带有工作箱,来自manual -

You can use the RequestDestination enumerate type of the destination of the request to determine a strategy. For example, when the target is data

:

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
      }),
    ],
  })
);

在普通的 Service Worker 中,您可以检查 request accept header

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

关于javascript - 服务人员 : How to cache images that do not have extensions using Workbox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55726483/

相关文章:

javascript - Workbox - 将 header 添加到缓存的响应

javascript - 排除 .module.less 的 .less 扩展文件的正则表达式

javascript - p5.j​​s 控制我播放的帧数

javascript - 如何让 <div> 以慢动作出现

javascript - Service Worker Install 事件与 Activate 事件

javascript - Service Worker 基本设置

javascript - 未缓存的请求可以绕过服务 worker 吗

javascript - 如何使用 Node.js 在非常简单的 JS 文件中编辑对象

service-worker - 在单页应用中检查 Service Worker 更新

javascript - AngularJS:ui-router 安全状态