Periodic Sync

Utilize the Periodic Sync API to efficiently retrieve updates when the app is closed. Contrary to the other features of this bundle, you will have to write few JS lines of code.

Service Worker Functions

To implement periodic tasks in your service worker, create a function for operations like cache cleaning or blog post retrieval.

In this example, we will ping the /ping endpoint, cache the response, and notify clients. This task will be registered and linked to the ping tag. The tag will be needed on the client side.

assets/sw.js
const ping = async () => {
  const cache = await openCache('ping-cache');
  const res = await fetch('/ping');
  await cache.put('/ping', res.clone());

  notifyPeriodicSyncClients('ping', { updated: true });
};

registerPeriodicSyncTask('ping', ping);

You can register multiple tasks under the same tag.

Client Site Fucntions

On the client side, we will need to tell the client to periodically execute the tasks registered with the defined tasks.

Now we prompt the client to perform the tasks under the ping tag every 6 hours.

assets/app.js
//... shortened for brevity

import {registerPeriodicSync} from '@spomky-labs/pwa/helpers';

await registerPeriodicSync('ping', 6 * 60 * 60 * 1000); //Every 6 hours in milliseconds

Last updated

Was this helpful?