3

I'm new on service worker in my page i have images without extensions [*.jpg, *.png and etc] like this "www.domain.com/api/media/a2b93f21-1acf-4e5e-9b19-6d7c68aaadc2" which i get them from API.

The following code work fine but not for this type of images

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

Any suggestion ?

denov
  • 11,180
  • 2
  • 27
  • 43
Maher
  • 2,517
  • 1
  • 19
  • 32
  • Couldn't you adjust your route rule to apply to anything on the `/api/media/` directory? Do you serve anything but images out of that? – zero298 Apr 17 '19 at 11:38
  • actually there is file manager to upload images and also get images by calling `media` from API, in the front we just get a `Guid` as filename. – Maher Apr 17 '19 at 13:30
  • One way to solve this problem would be to check the headers of the requested file. If the headers tell the SW that the requested entity is an image file, then cache it. – pate Apr 17 '19 at 17:32

1 Answers1

4

with workbox, from the 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
      }),
    ],
  })
);

in a plain vanilla service worker you can check the request accept header

if (request.headers.get('Accept').indexOf('image') !== -1) { 
    ... stash in cache ...
} 
denov
  • 11,180
  • 2
  • 27
  • 43
  • Thanks @denov for your time to answer, i will test it & i don't forget rate your answer. – Maher Apr 25 '19 at 04:49
  • @denov Hello, could you check this question out? https://stackoverflow.com/questions/64117929/workbox-service-worker-maxageseconds-query – Nevin Madhukar K Sep 29 '20 at 10:51