


We use cookies to improve your experience
We use essential cookies to make our site work. With your consent, we may also use non-essential cookies to improve user experience.
Definition
A Service Worker is a JavaScript file that runs in the background of a web browser, separate from the web page. It intercepts network requests, manages cache, enables offline functionality, and handles push notifications — forming the backbone of Progressive Web Apps (PWAs).
A Service Worker runs on a separate thread from the main page, meaning it cannot access the DOM directly. Instead, it acts as a programmable network proxy — every HTTP request the page makes passes through the Service Worker first. This allows it to serve cached responses when offline, update stale content in the background, and implement sophisticated caching strategies. Service Workers only work on HTTPS origins (plus localhost for development).
The power of Service Workers lies in caching control. Common strategies include: Cache First (serve from cache, fall back to network — fast but potentially stale), Network First (try network, fall back to cache — fresh but slower offline), and Stale While Revalidate (serve from cache immediately, then update the cache from the network in the background — a balance of speed and freshness). Libraries like Workbox from Google simplify implementing these strategies.
Service Workers enable push notifications (receiving messages from a server even when the site is not open), background sync (deferring actions like form submissions until the network is available), and periodic background sync (checking for updates on a schedule). These capabilities, combined with a web app manifest, are what make a website qualify as a PWA. The lifecycle (install, activate, fetch events) gives developers fine-grained control over when and how the Service Worker takes over network handling.