Skip to content Skip to sidebar Skip to footer

Using Service Workers To Both Use Cache *and* Update In Background

I understand that ServiceWorkers can grab responses out of cached network requests. That said, is it possible to have these workers continue to update the cache in the background?

Solution 1:

What you're describing is very similar to the stale-while-revalidate strategy.

The basic recipe in that cookbook doesn't include any code for having the service worker notify the client page(s) when the revalidation step finds an update, though.

If you were to use Workbox inside your service worker, you could accomplish that notification step using the workbox-broadcast-update module along with a few other modules:

In your service worker:

import {registerRoute} from'workbox-routing';
import {StaleWhileRevalidate} from'workbox-strategies';
import {BroadcastUpdatePlugin} from'workbox-broadcast-update';

registerRoute(
  // Adjust this to match your cached data requests:newRegExp('/api/'),
  newStaleWhileRevalidate({
    plugins: [
      newBroadcastUpdatePlugin(),
    ],
  })
);

In your web app:


navigator.serviceWorker.addEventListener('message', async (event) => {
  // Optional: ensure the message came from workbox-broadcast-updateif (event.data.meta === 'workbox-broadcast-update') {
    const {cacheName, updatedUrl} = event.data.payload;

    // Do something with cacheName and updatedUrl.// For example, get the cached content and update// the content on the page.const cache = await caches.open(cacheName);
    const updatedResponse = await cache.match(updatedUrl);
    const updatedText = await updatedResponse.text();
  }
});

Post a Comment for "Using Service Workers To Both Use Cache *and* Update In Background"