1

workboxSW.precache is cacheFirst by default, is there a way to change its strategy?

workboxSW.precache(myPrecacheItems);

Or is there a way to define the cache name on precache items, so precache items can be overwrite by specifying route?

codejockie
  • 9,020
  • 4
  • 40
  • 46
seUser
  • 1,093
  • 2
  • 10
  • 21

2 Answers2

0

precache is basically meant for your static assets like css/js etc. To these assets even if you don't append a hash, workbox will append a hash while precaching.

So if you change these, a new sw will come into play and new bundles will be served.

Whereas staleWhileRevalidate is a runtime strategy(basically used for dynamic data e.g. APIs). you can add runtime handler in workbox for these and expect them to work.

If you still think that you need precache with a runtime strategy, please elaborate your use case.

prateekbh
  • 273
  • 1
  • 6
0

While I don't know if it's possible to change the workbox.precache strategy, I believe what you want to do is fill your routing cache with some pages on service worker install.

To do this first create your workbox route with staleWhileRevalidate strategy with a defined cache name:

workbox.routing.registerRoute(
    /.*\.html/,
    workbox.strategies.staleWhileRevalidate({  
        cacheName: 'MY-CACHE',
    })
);

To precache some urls for your defined route on SW install. Add this code to your Service Worker:

self.addEventListener('install', (event) => {
    const urls = ['https://url1.html','https://url2.html','etc'];
    event.waitUntil(caches.open('MY-CACHE').then((cache) => cache.addAll(urls)));
});

Where MY-CACHE is the name of the cache set in your staleWhileRevalidate strategy.

Andyba
  • 421
  • 3
  • 10