service worker is a JavaScript Worker script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction. Today, they already include features like push notifications and background sync

Service Worker’s Core Feature

The core feature discussed in this tutorial is the ability to intercept and handle network requests, including programmatically managing a cache of responses

Prerequisite Reading

Things to Note About a Service Worker

  • service worker is a JavaScript Worker, so it can’t access the DOM directly. Instead, a service worker can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM if needed.
  • service worker is a programmable network proxy, allowing you to control how network requests from your page are handled.
  • service worker is terminated when not in use, and restarted when it’s next needed, so you cannot rely on global state within a service worker’s onfetch and onmessage handlers. If there is information that you need to persist and reuse across restarts, service workers do have access to the IndexedDB API.
  • service workers make extensive use of promises

Service Worker Prerequisites

Service Worker Life Cycle

1. Register a Service Worker

after a service worker is registered the browser installs it

2. Install Event

After a service worker is installed and the user navigates to a different page or refreshes, the service worker will begin to receive fetch events, an example of which is below (a service worker would only see fetch events based on how the service worker was registered)

3. Fetch Event

4. Activate Event (When New Service Worker Replaces Old One)

5. Putting It All Together

Other Examples