What are Service Workers?
A service worker is a special type of web worker that acts as a proxy between your web app and the network. It can intercept requests, serve cached responses, and work offline. Service workers are the foundation of Progressive Web Apps (PWAs).
// Register a service worker
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/sw.js")
.then(reg => console.log("Registered:", reg.scope))
.catch(err => console.log("Registration failed:", err));
}
Installing and Activating
Service workers have a lifecycle: install, activate, and idle. During installation, you typically cache important assets. During activation, you clean up old caches.
// sw.js
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open("v1").then(cache => {
return cache.addAll([
"/",
"/styles.css",
"/script.js",
]);
})
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then(keys => {
return Promise.all(
keys.filter(key => key !== "v1").map(key => caches.delete(key))
);
})
);
});
Intercepting Requests
The fetch event lets you intercept network requests and respond with cached data or fetch from the network as a fallback.
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
});
Try it Yourself →
Caching Strategies
There are several patterns for caching. Cache-first serves from cache, network-first tries the network, and stale-while-revalidate serves the cache while updating it in the background.
// Stale-while-revalidate pattern
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.open("v1").then(cache => {
return cache.match(event.request).then(cached => {
const fetched = fetch(event.request).then(response => {
cache.put(event.request, response.clone());
return response;
});
return cached || fetched;
});
})
);
});
Summary
Service workers enable offline support and caching for your web app. They intercept requests and serve cached responses. Use them to build fast, reliable Progressive Web Apps.