Service Worker

A service worker is a script that the browser can run separately from a page to handle selected events such as requests, caching, and push messages.

What you will learn

Registering a worker

if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/service-worker.js').catch((error) => console.error('Registration failed', error)); }

Registration is restricted by scope and secure-context rules. The worker does not automatically control the current page until the browser installs and activates it.

Caching needs a policy

A cache can make a page load when the network is unavailable, but it can also serve old content. Version caches, remove old entries during activation, and decide what should go to the network first.

Common mistakes