A script that runs in the background, enabling offline functionality, push notifications, and caching for web applications.
A Service Worker is a JavaScript file that runs in the background, separate from your web page. It intercepts network requests, manages caching, and enables offline functionality.
Think of it as a programmable proxy between your web app and the network.
Offline Access: Cache assets so your app works without internet.
Background Sync: Queue actions when offline, sync when online.
Push Notifications: Receive notifications even when site is not open.
Faster Loading: Serve cached content instantly instead of fetching from network.
Service Workers sit between your app and the network. When your app makes a request, the Service Worker intercepts it and decides whether to fetch from network or serve from cache.
Install: Service Worker downloads and installs, caching initial assets.
Activate: Old Service Worker replaced, new one takes control.
Fetch: Intercepts network requests, serves cached or fresh content.
: Check cache, fetch from network only if not cached. Fast for static assets.
No related topics found.
Network First: Try network, fall back to cache if offline. Good for dynamic content.
Stale While Revalidate: Serve cached version immediately, update cache in background.
Twitter Lite: Works offline using Service Workers, loads instantly.
Pinterest: Caches images aggressively, provides offline browsing.
Spotify Web Player: Caches recently played songs for offline playback.
Service Workers are core to PWAs. They enable offline functionality, making web apps feel like native apps.
Supported in all modern browsers. Not supported in IE11 (but IE11 is dead anyway).
Service Workers only work over HTTPS. This prevents man-in-the-middle attacks where someone could inject malicious Service Workers.
Exception: localhost works without HTTPS for development.
No DOM Access: Cannot directly manipulate the page.
Separate Thread: Runs independently, cannot access page variables.
Async Only: All APIs are promise-based, no synchronous operations.
Register a Service Worker in your main JavaScript file. The Service Worker script handles caching and network interception.
Not Updating: Browsers aggressively cache Service Workers. Use versioning.
Overly Aggressive Caching: Cache everything and users see stale content forever.
Complex Logic: Service Workers should be simple. Complex logic causes bugs.
Workbox: Google library that simplifies Service Worker development.
Create React App: Includes Service Worker template.
Next.js: Built-in Service Worker support with next-pwa.
Service Workers power modern web experiences. They enable offline functionality, faster loading, and push notifications.
Not every site needs Service Workers, but for apps where offline access or performance matters, they are essential.