Track 02 · Lesson 17 of 17Inside the browser

Track 02 · Inside the browser

Service workers and offline

Lesson 17 of 17· 7 min

A service worker is a script that sits between your page and the network. It can answer requests from a cache, so the app loads instantly and even works offline. That's the core of a Progressive Web App (PWA). Choose a strategy and a network condition.

Pick a strategy

Try each one offline

Network

What’s being requested

Service worker strategy

Pick options and press Load it.

// No service worker: every request goes to the network

The three strategies#

  • Cache first: answer from the cache, and only go to the network if there's nothing saved. Instant and offline-proof, but it can serve stale data. Ideal for versioned app files.
  • Network first: try the network, save a copy, and fall back to the cache when offline. Always current when it can be. Ideal for data that must be fresh.
  • Stale while revalidate: answer from the cache immediately, and fetch a fresh copy in the background for next time. Ideal for things that can be a little old, like avatars or article lists.

Handle with care#

A service worker keeps running across visits, and it can keep serving old files long after you deploy. Version your caches, delete old ones when a new worker activates, and test the update path. Service workers only run on HTTPS (and localhost). Libraries like Workbox handle most of the details.

Check yourself

Which strategy fits today's stock prices, which must be current but should still show something offline?