s-leg3ndz
s-leg3ndz

Reputation: 3518

Workbox cache URLs from message event

I try to add some routes in cache using message event.

On every page, there are several on dynamic that I would like to keep in cache. For this, i send an array of URL to my Service Worker on document load :

window.addEventListener('load', () => {
  if (serviceWorker.isServiceWorkerSupported()) {
    serviceWorker.register();

   if (typeof PRECACHE_ROUTES !== 'undefined') {
      serviceWorker.sendPreCacheRoutesToSW(PRECACHE_ROUTES);
    }
  }
});

But, with this method, if user have no network, the StaleWhileRevalidate same not work, you can see an example :

registerRoute(
  '/',
  new StaleWhileRevalidate({
    cacheName: 'routes', // Work on offline
    plugins,
  }),
);

self.addEventListener('message', event => {
  if (event.data && event.data.type === 'PRECACHE_ROUTES') {
    event.data.routes.forEach(route => {
      registerRoute(
        route,
        new StaleWhileRevalidate({
          cacheName: 'routes', // Not work on offline
        }),
      );
    });

    event.waitUntil(
      caches.open('routes').then(cache => cache.addAll(event.data.routes)),
    );
  }
});

All urls are well cached, but do not seem to be taken into account offline.

Anyone can help me ?

Upvotes: 0

Views: 677

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56044

I would suggest following this recipe using workbox-window and workbox-routing to accomplish that:

// From within your web page, using workbox-window:
const wb = new Workbox('/sw.js');

wb.addEventListener('activated', (event) => {
  // Get the current page URL + all resources the page loaded.
  // Replace with a list of URLs obtained elsewhere, as needed.
  const urlsToCache = [
    location.href,
    ...performance.getEntriesByType('resource').map((r) => r.name),
  ];
  // Send that list of URLs to your router in the service worker.
  wb.messageSW({
    type: 'CACHE_URLS',
    payload: {urlsToCache},
  });
});

// Register the service worker after event listeners have been added.
wb.register();

This will automatically apply the routes defined in your service worker to the URLs you provide in the payload.

Dynamically setting up routes for those URLs inside of your message event isn't going to give you the behavior you're after, as you've found.

Upvotes: 2

Related Questions