Service workers

Definition

A service worker is a 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 notificationsarrow-up-right and background syncarrow-up-right. The core feature is the ability to intercept and handle network requests, including programmatically managing a cache of responses.

Things to note about a service worker:

  • It's a JavaScript Workerarrow-up-right, 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 postMessagearrow-up-right 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.

  • It's 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 APIarrow-up-right.

  • Service workers make extensive use of promises.

The service worker life cycle

Prerequisites

  • Browser support

  • HTTPS

Last updated