Service Workers are background scripts that run in the browser separately from the web page. They enable features like offline support, caching, and push notifications, which are essential for Progressive Web Apps (PWAs).
1️⃣ Key Features of Service Workers
- Intercept network requests → serve cached content when offline
- Cache static assets → faster load times
- Background sync → sync data when the network is available
- Push notifications → engage users even when app is closed
2️⃣ How They Work in React (PWA)
- Create React App (CRA) includes a service worker setup for PWAs
- Service workers cache static files like JS, CSS, and images
- When the app loads:
- Browser registers the service worker
- Service worker caches assets
- On subsequent visits, it serves cached files first, then fetches updates
3️⃣ Registering a Service Worker in React
// index.js (CRA)
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import * as serviceWorkerRegistration from "./serviceWorkerRegistration";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
// Register service worker
serviceWorkerRegistration.register();
serviceWorkerRegistration.register()enables offline caching- You can also unregister if you don’t want PWA features:
serviceWorkerRegistration.unregister();
4️⃣ Example: Caching API Data
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
- Checks cache first → returns cached response if available → else fetches from network
5️⃣ Benefits in React PWAs
- Offline Support: Users can access the app without an internet connection
- Faster Load Times: Cached assets load instantly
- Background Sync: Push or sync updates when online
- Improved User Experience: App feels like a native mobile app
⚡ In short:
Service workers are background scripts that enable React apps to work offline, cache assets, and handle push notifications. They are a core part of Progressive Web Apps (PWAs) and improve performance and reliability.