A service worker is a JavaScript file that the browser runs in the background, separately from your pages. Once installed, it sits between your site and the network like a programmable proxy: every request your pages make, for HTML, CSS, images or API data, passes through it first.
That one position is what makes PWAs reliable. The service worker can answer a request from its own cache, fetch it from the network, or build a response on the spot, so your app can open instantly and keep working offline.
Key facts
- It runs on its own thread, with no access to the DOM. It talks to pages with
postMessage. - It is event-driven: the browser starts it when there is something to do (a request, a push message) and stops it when it is idle. Do not keep state in global variables; use the Cache API or IndexedDB.
- It only works on HTTPS (and
localhost). - It has a scope: it controls pages under the folder it is served from. A file at
/sw.jscontrols the whole site; one at/app/sw.jscontrols only/app/. - It does not control the page that registered it until the next navigation, unless it calls
clients.claim().
Registering one
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js', { scope: '/' })
.then((reg) => console.log('Service worker scope:', reg.scope))
.catch((err) => console.error('Registration failed:', err));
});
}
Registering after load keeps the first visit fast: the worker downloads and installs while the visitor reads.
The three events that matter
// 1. install: runs once per version. Precache what the app needs to start.
self.addEventListener('install', (event) => {
event.waitUntil(caches.open('shell-v1').then((cache) => cache.addAll(['/', '/offline.html', '/app.css', '/app.js'])));
});
// 2. activate: the new version takes over. Clean up old caches.
self.addEventListener('activate', (event) => {
event.waitUntil(caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== 'shell-v1').map((k) => caches.delete(k)))));
});
// 3. fetch: every request from controlled pages.
self.addEventListener('fetch', (event) => {
event.respondWith(caches.match(event.request).then((hit) => hit || fetch(event.request)));
});
Other events: message (from pages), push and notificationclick (push), sync and periodicsync (background sync), and backgroundfetchsuccess (background fetch).
What service workers can do
- Serve pages and files from cache: caching strategies
- Show a custom offline page
- Receive push messages and show notifications, even when no tab is open
- Retry failed requests later with Background Sync
- Download large files in the background with Background Fetch
- Speed up navigations with navigation preload and streaming
What they cannot do
- Touch the DOM, or use
localStorageor synchronous XHR. - Run forever: browsers stop idle workers after about 30 seconds, and limit long tasks.
- Intercept requests from pages outside their scope, or the very first page load before installation.
The lifecycle in one sentence
A new service worker installs, then waits until no page uses the old version, then activates and starts handling fetches. Understanding that waiting step is the key to shipping updates without breaking things: read the service worker lifecycle and updates.
Do I write it by hand?
For small sites, yes: it is a few dozen lines, and our service worker generator writes a solid starting point. For bigger apps, libraries like Workbox and Serwist handle precache manifests, routing, expiration and edge cases: see Workbox and Serwist.
Compatibilidade de navegadores
| Recurso | Chrome / Edge desktop | Chrome Android | Safari iOS / iPadOS | Safari macOS | Firefox desktop | Firefox Android | Samsung Internet |
|---|---|---|---|---|---|---|---|
| Service workers | Chrome / Edge desktop: Sim | Chrome Android: Sim | Safari iOS / iPadOS: Sim | Safari macOS: Sim | Firefox desktop: Sim | Firefox Android: Sim | Samsung Internet: Sim |
| Navigation preload | Chrome / Edge desktop: Sim | Chrome Android: Sim | Safari iOS / iPadOS: Sim | Safari macOS: Sim | Firefox desktop: Sim | Firefox Android: Sim | Samsung Internet: Sim |