Offline content caching using Service Worker

29 Jun 2019

One of the major feature PWA offers - is the rich offline experience made feasible on web through service worker.

A service worker is a script that runs in the background, separate from a web page. It opens-up the door to features that don't need a web page or user interaction.

Service worker allows you to intercept all the network request and reply back with custom content like a network proxy. This enables developer to create application that are accessible and use-able even when it is offline. Further, library like Workbox makes it possible for adding offline support for the web apps.

Workbox is a library that bakes in a set of best practices and removes the boilerplate every developer writes when working with service workers.

Following are few use-cases where you can utilize a Service Worker with Workbox for its offline support

  1. Provide Save Later button on your article/news pages.
  2. Pro-actively cache top 10 article pages on your homepage, so that user can read those pages even when network is down.
  3. Cache JavaScripts, HTML structures, CSS, ajax content etc.,
  4. Reduce TTFB (Time To First Byte) on subsequent user visits by caching site skeleton and reading it from the cache.

Following sample service worker file shows how you can use cache strategy offered by Workbox library and enable offline experience for you application.

// sw.js

// Precache Files with Webpack
workbox.precaching.precacheAndRoute(self.__precacheManifest || []);

// Cache the fontawesome fonts.
workbox.routing.registerRoute(
    /^https:\/\/netdna\.bootstrapcdn\.com\/font-awesome\/4\.7\.0\//,
    new workbox.strategies.CacheFirst({
        cacheName: 'fontawesome-fonts-stylesheets',
        plugins: [
            new workbox.expiration.Plugin({
                maxEntries: 30,
            }),
            new workbox.cacheableResponse.Plugin({
                statuses: [0, 200]
            })
        ]
    }),
);

// Cache the Google fonts.
workbox.routing.registerRoute(
    new RegExp('https://fonts.(?:googleapis|gstatic).com/(.*)'),
    workbox.strategies.cacheFirst({
        cacheName: 'google-fonts',
        plugins: [
            new workbox.expiration.Plugin({
                maxEntries: 30,
            }),
            new workbox.cacheableResponse.Plugin({
                statuses: [0, 200]
            })
        ],
    }),
);

// Cache the site images.
workbox.routing.registerRoute(
    /\/img\/*/i,
    new workbox.strategies.CacheFirst({
        cacheName: 'pwa-sample-images',
        plugins: [
            new workbox.expiration.Plugin({
                // Only cache requests for a week
                maxAgeSeconds: 7 * 24 * 60 * 60,
                // Only cache 10 requests.
                maxEntries: 30
            }),
            new workbox.cacheableResponse.Plugin({
                statuses: [0, 200]
            })
        ]
    }),
);

 For a complete working example, visit following demo page that loads up in a flash on repeated visits.

 https://davidsekar.github.io/pwa-sample/

For further in-depth reading;

https://developers.google.com/web/fundamentals/primers/service-workers/

Related Posts