The starters guide to service workers

How to make websites work offline

Offline websites with service workers

Basics

The general approach is, to check for new content, whenever there is an internet connection (or access to WLAN) and display it on demand. The service worker is just a fancy piece of JavaScript, which we can install into a clients browser and which will then run independently of the server itself, without needing an active connection.

  • the service worker itself, which must be it’s own file
  • the registration of this service worker, which can be inline

Registering the service worker

Assuming the service-worker is deployed at /js/service-worker.js, the registration script should look like this:

register.js

Writing the service worker

Install-event

Contrary to many tutorials out there, we don’t need an ’install’-event listener, but it’s nice to have one, in order to see, if the registration succeeded:

hooking install-event

Fetch-event

If we want subsequent page-loads to work without network, we need to handle fetch-events in our service worker. A fetch event occurs, whenever a new location is queried from outside the service worker, for example from another script or a source in the HTML itself.

fromNetwork function
fromCache function
fetch-event listener

Hardcoded prefetching of resources

We will now write a function to prefetch resources, first by hardcoding, then by dynamically asking the server which URLs to fetch.

static prefetch

Dynamic prefetching of resources

Now that’s great and all, but hardcoding URLs only makes sense for some resources or if there is a build process for the website, which is able to auto generate these URLs.

dynamic prefetch
setInterval(() => prefetchStuffDynamic, 10000)

Offline indicator

Finally, we probably want a visible indicator, if our page is currently displayed in offline mode. For this we can use the event-listeners “online” and “offline”. They can be added like this, outside of the context of the service worker (e.g. in the registration script):

offline indicator event-hooks
offline indicator (HTML)
offline indicator switch

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yannik Schmidt

Python programmer at heart, Linux Expert at work, GameDev on my good days, web developer on the bad days.