Add Offline Support to WordPress with Service Workers and Workbox

Offline support for a WordPress site with a service worker and Workbox

A service worker is a script that the browser runs between the page and the network. It can answer requests from a cache, so pages the visitor has seen, or pages the site marks as important, open without a connection. For an event site whose attendees check the schedule in a basement hall without signal, that is the difference between useful and useless. Workbox, Google’s service worker library, handles the caching strategies.

Problem: A conference site should show the schedule, the speakers and the venue page offline, and display a friendly page instead of the browser’s error for everything else.

Solution: Build a service worker with Workbox that precaches the key pages and an offline page, serves navigations network-first with the cache as fallback, serves CSS, JavaScript and images from the cache, serve the file from the site root through a rewrite rule so it controls the whole site, and register it from the theme.

The service worker

// src/sw.js, bundled with workbox-build or a bundler into the theme's build/sw.js
import { precacheAndRoute, matchPrecache } from 'workbox-precaching';
import { registerRoute, setCatchHandler } from 'workbox-routing';
import { NetworkFirst, StaleWhileRevalidate, CacheFirst } from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';

precacheAndRoute( [
    { url: '/schedule/', revision: '2024-02-15' },
    { url: '/speakers/', revision: '2024-02-15' },
    { url: '/venue/', revision: '2024-02-15' },
    { url: '/offline/', revision: '2024-02-15' },
] );

registerRoute(
    ( { request, url } ) => request.mode === 'navigate' && ! url.pathname.startsWith( '/wp-admin' ),
    new NetworkFirst( { cacheName: 'pages', networkTimeoutSeconds: 3 } )
);

registerRoute(
    ( { request } ) => [ 'style', 'script' ].includes( request.destination ),
    new StaleWhileRevalidate( { cacheName: 'assets' } )
);

registerRoute(
    ( { request } ) => request.destination === 'image',
    new CacheFirst( {
        cacheName: 'images',
        plugins: [ new ExpirationPlugin( { maxEntries: 80, maxAgeSeconds: 30 * 24 * 60 * 60 } ) ],
    } )
);

setCatchHandler( async ( { request } ) => {
    if ( request.mode === 'navigate' ) {
        return ( await matchPrecache( '/offline/' ) ) || Response.error();
    }
    return Response.error();
} );

The pages are tried on the network first and fall back to the cached copy after three seconds; that keeps online visitors on fresh content. Assets are served from the cache and updated in the background. The revision values tell Workbox when to download a precached page again: change them when the schedule changes. Admin pages, the login and the REST API are never cached here; do not add them.

Serve it from the root

A service worker controls only URLs below its own path. Served from /wp-content/themes/..., it would control nothing but the theme folder. A rewrite rule serves it as /sw.js:

add_action( 'init', function () {
    add_rewrite_rule( '^sw\.js$', 'index.php?ha_sw=1', 'top' );
} );

add_filter( 'query_vars', function ( $vars ) {
    $vars[] = 'ha_sw';
    return $vars;
} );

add_action( 'template_redirect', function () {
    if ( get_query_var( 'ha_sw' ) ) {
        header( 'Content-Type: application/javascript; charset=utf-8' );
        header( 'Cache-Control: no-cache' );
        readfile( get_theme_file_path( 'build/sw.js' ) );
        exit;
    }
} );

Flush the rewrite rules once (Settings, Permalinks, Save). no-cache makes the browser check for a new service worker on every visit. Rewrite rules in general: custom rewrite rules.

Register it

if ( 'serviceWorker' in navigator ) {
    window.addEventListener( 'load', () => {
        navigator.serviceWorker.register( '/sw.js' );
    } );
}

Service workers run only on HTTPS (and on localhost for development).

NOTE: A broken service worker can keep serving old pages to returning visitors until it is replaced, so test updates on staging and keep a “kill switch” ready: a sw.js that only calls self.registration.unregister(). Logged-in users and WooCommerce carts must never be cached by it; a site with a shop or a membership area should precache only public, static pages.