Offline First: An Intro to Service Workers

Let’s assume our users will always have a fast, reliable internet connection. – No One Ever

It seems ridiculous to say it out loud, but that’s how we’ve built websites and applications in the past. The goal of an “offline first” strategy is to assume the opposite: our users have a slow, unreliable internet connection. Why? Because network awareness is a good user experience in any context.

What’s a Service Worker?

A generic entry point for persistent event-driven background processing in the Web Platform. – Paraphrased from the W3C Spec

A service worker is essentially a background script for controlling web pages. This provides application authors the low-level control over the request lifecycle required to deliver a great user experience with low connectivity.

Service Worker Features

  • Intercept network requests
  • Requests caching
  • Push notifications
  • Background sync (proposed)
  • Geo-fencing (proposed)

Service Worker Demos

These examples assume familiarity with:

Example 1: Service Worker Lifecycle

Demo on Github

Registering a Service Worker
The Service Worker Script
Log output on first load
Log output on second load

Example 2: Fetching

Demo on Github

Custom Responses from a Service Worker
Please don’t do this…

Example 3: Prefetching & Caching

Demo on Github

Prefetching Assets
Prefetching Network Log
Cache First Fetching Strategy
  1. If there is no response, fallback to the default behavior of fetching.
Loading Assets From The Cache
Invalidating Stale Cache

Example 4: Offline Page

View Full Demo on Github

Prefetching an Offline Page
Offline Page Fallback
Our Offline Page In-action

  • Added a fallback offline page when the user loses their connection.

LocalMed Engineering

LocalMed’s engineering and product development blog. https://www.localmed.com

Peter Browne

Written by

Product Designer/Developer @ LocalMed

LocalMed Engineering

LocalMed’s engineering and product development blog. https://www.localmed.com