Skip to content

Service Worker

In one line

A service worker is a JavaScript file that runs in the background, enabling offline support, push notifications, and caching for web apps.

In simple words

A service worker is a special JavaScript script that the browser runs in the background, separate from your web page. It cannot access the DOM directly but can intercept network requests, cache responses, and handle events like push notifications — even when the page is closed.

Service workers are the core technology behind Progressive Web Apps (PWAs). They enable offline functionality by caching resources, background sync, and push notifications. They run on a separate thread and have a specific lifecycle: install → activate → fetch.

To use a service worker, you register it from your page with navigator.serviceWorker.register('/sw.js'). The service worker file then listens for install, activate, and fetch events to manage caching and offline behavior.

Example

javascript
// In sw.js (service worker)
self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then((cached) => {
      return cached || fetch(event.request);
    })
  );
});

A service worker that serves cached responses when available, falling back to the network for uncached requests.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary