Suggest an editImprove this articleRefine the answer for “What does a Service Worker do?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)A **Service Worker** is a special background script that the browser runs between the page and the network, and which can intercept network requests, cache responses, and react to events (fetch, push, sync) even when the tab is closed. **Key point:** in simple terms, it's a "proxy server inside the browser".Shown above the full answer for quick recall.Answer (EN)Image## What a Service Worker is > A **Service Worker** is a special background script > that the browser runs **between the page and the network**, > and which can **intercept network requests**, > **cache responses**, and **react to events** (fetch, push, sync) > even when the tab is closed. In simple terms, it's a "proxy server inside the browser". --- ## How it works (architecturally) ```javascript ┌──────────────┐ │ Internet │ └──────▲───────┘ │ │ (fetch request) ▼ ┌────────────────────┐ │ Service Worker │ ← a "proxy" between the page and the network │ ├ intercept fetch()│ │ ├ serve from cache │ │ ├ push notifications│ │ └ background sync │ └────────▲────────────┘ │ │ ┌────────────────────┐ │ Site tab │ └────────────────────┘ ``` --- ## Service Worker lifecycle 1. **Registration** The site tells the browser where the worker is: ```javascript navigator.serviceWorker.register('/sw.js'); ``` 2. **Install** The worker is downloaded and installed (once). 3. **Activate** Old versions are removed, the new worker becomes active. 4. **Running (fetch / push / sync)** After activation, the worker listens for events: - `fetch` intercepts requests; - `push` handles notifications; - `sync` handles background tasks. 5. **Idle / terminate** When not in use, the browser unloads it from memory, and starts it again on the next event. --- ## Example: a basic Service Worker `sw.js` ```javascript self.addEventListener('install', (event) => { console.log('Service Worker installing...'); event.waitUntil( caches.open('v1').then(cache => cache.addAll([ '/', '/index.html', '/styles.css', '/app.js' ])) ); }); self.addEventListener('activate', () => { console.log('Service Worker activated!'); }); self.addEventListener('fetch', (event) => { console.log('Request intercepted:', event.request.url); event.respondWith( caches.match(event.request).then(response => { return response || fetch(event.request); // from cache or from the network }) ); }); ``` This SW: - saves files to the cache on install, - intercepts all requests, - serves from the cache if it exists, - otherwise goes to the network. --- ## Example of registration in the main code ```javascript if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then(() => console.log('SW registered')) .catch(console.error); } ``` --- ## Main Service Worker capabilities | Capability | What it does | |---|---| | **Fetch interception** | Intercepts and controls all network requests | | **Caching API** | Stores files and responses in a cache (offline support) | | **Background sync** | Runs tasks once the network is back | | **Push notifications** | Receives push notifications from the server | | **Offline-first** | Lets the site work without internet | | **Periodic sync** | Runs actions on a schedule | | **Proxy layer** | Improves security (controls requests and responses) | --- ## Example of an offline page ```javascript self.addEventListener('fetch', (event) => { event.respondWith( fetch(event.request).catch(() => caches.match('/offline.html')) ); }); ``` If there is no internet, it returns `/offline.html` so the site doesn't break, it shows "You are offline". --- ## Push notifications ```javascript self.addEventListener('push', (event) => { const data = event.data.json(); event.waitUntil( self.registration.showNotification(data.title, { body: data.body, icon: '/icon.png' }) ); }); ``` Works even when the tab is **closed**, the browser "wakes" the Service Worker to handle `push`. --- ## Background Sync Lets you run deferred tasks once the network is back: ```javascript self.addEventListener('sync', (event) => { if (event.tag === 'sendFormData') { event.waitUntil(sendDataToServer()); } }); ``` For example, the user is offline, data is saved to IndexedDB, and once the network is back, the Service Worker sends it to the server itself. --- ## Limitations | Feature | Description | |---|---| | Isolated from the DOM | No `window`, `document` | | HTTPS only | Works only on secure domains (or [localhost](http://localhost)) | | Limited memory access | There are cache quotas | | Unloaded automatically | "Wakes up" on events, does not run continuously | --- ## Where it's actually used - **PWA (Progressive Web Apps)** - offline access, "Add to Home Screen", instant loading - **News / chat apps** - push notifications without an open tab - **Games / offline modes** - loading assets and data into the cache - **Web services** - caching API responses, saving traffic --- ## A simple analogy > Imagine the Service Worker as the **site's guard** > > - it stands "at the door" between the page and the internet, > - it decides: "serve from the cache or go to the network", > - it can show notifications, > - it keeps working even when the shop (the tab) is closed. --- ## Summary | Parameter | Description | |---|---| | **Type** | A background JS process between the page and the network | | **Main functions** | Intercepting requests, cache, push, background sync | | **Works with the tab closed** | Yes | | **DOM access** | None | | **Requires HTTPS** | Yes | | **Main use** | PWA, offline mode, notifications |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.