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
- What a service worker can and cannot do
- How to register one from a page
- Why cache versioning and update testing matter
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
- Do not cache every response without considering private or changing data.
- Test a new release after an old worker has already been installed.
- Provide a network fallback and a clear update path.