minimal-sw-caching

This page is a minimal implementation of the stale-while-revalidate caching strategy using service workers.

To demonstrate the caching, I've implemented a simple API. The /api endpoint on this domain returns the current timestamp rounded down to the nearest 10 second mark.

However, this API has a hardcoded delay of 1 second to simulate a slow network.

The following timestamp was fetched from /api:

Fetching timestamp...

Wait 10 seconds, then refresh this page.

If you refreshed the page, you'll see the old timestamp was served immediately. That's the "stale" content that the service worker cached.

However, the original network request to /api continued in the background. That's the "revalidate" part of this strategy.

And if the /api response differs from the cached content, a notification dialog appears.

This pattern is common in native apps, but surprisingly difficult to implement on the web.

Using modern web APIs, this capability was implemented in about 35 lines of JavaScript.

Click here to view the source code on GitHub.

An updated version of this page is available.

Refresh