Member-only story
Cache Website Assets in “Offline Mode”
Using a JavaScript Service Worker
An “Offline Mode” can be an added benefit if you are building on a normal web app, or a required feature if you are building a Progressive Web App. The most basic version of an offline mode is a cache of static assets and a way to access them when offline.
In this post, we’ll write a Service Worker and build an offline mode for a JS app with a live demo here.
Service Workers
A Service Worker is a Javascript process that acts as middleware for your application, processing the outgoing and incoming requests from your webpage to the internet.
It is similar to a Web Worker, in that it runs in the browser on a separate, non-blocking thread, without access to the DOM. Unlike a Web Worker, it has a specific set of custom methods and properties that allow it to handle and cache all network requests coming from your application. If you want to deep dive into the features of Service Workers I suggest you read the MDN Specification.
The ability to intercept and cache network requests from a given web page makes the service worker the perfect tool for implementing the offline mode!
Initiating the service worker
The way that we initiate a Service Worker is as follows. We will need to add this line to the primary script (index.js
).
This line will run the Service Worker script and start the SW running in your browser.
Obviously this will not work as we haven’t actually written the web worker script that will be run by the browser when we call serviceWorker.register()
.
Let’s start with the code below, inserted into another file called sw.js
: