Service Worker Builder
Generate a production-ready service worker with configurable caching strategies, precaching, offline fallback, and background sync. Choose your routes, pick your strategies, and get copy-ready code.
Default Caching Strategy
Cache First
Serve from cache, fall back to network. Fastest responses.
Network First
Try network, fall back to cache. Always fresh.
Stale While Revalidate
Serve cache immediately, update in background.
Network Only
Always fetch from network. No caching.
Route-Specific Strategies
Precache Files
Options
Service Worker Fundamentals
A service worker is a JavaScript file that the browser runs in the background, separate from your web page. It sits between your application and the network, intercepting every HTTP request your page makes. This proxy position gives it extraordinary power: it can serve responses from a local cache instead of the network (enabling offline functionality), modify requests and responses in-flight, manage a sophisticated multi-layered cache, receive push notifications even when your page is closed, and synchronize data in the background when connectivity is restored.
Service workers have a distinct lifecycle with three phases: registration (your page tells the browser where to find the service worker file), installation (the service worker downloads and caches essential resources), and activation (the service worker takes control of pages and begins intercepting requests). Understanding this lifecycle is crucial because it dictates when cached resources are available and when old caches are cleaned up. A newly installed service worker does not take control until all tabs using the old version are closed, unless you explicitly call skipWaiting().
Caching Strategies Deep Dive
Cache First (Offline First)
The cache-first strategy checks the cache before the network. If a cached response exists, it is returned immediately (in under 1ms) without any network request. If the resource is not in the cache, it is fetched from the network and the response is cached for future use. This strategy provides the fastest possible response times and works offline for any previously visited page. The tradeoff is staleness: users may see outdated content until the cache is updated. This is ideal for static assets (CSS, JS, images, fonts) that have versioned filenames and rarely change at the same URL.
Network First (Freshness First)
The network-first strategy always tries the network first. If the network request succeeds, the response is returned and cached. If the network fails (offline or timeout), the cached response is returned as a fallback. This ensures users always see the latest content when online while still providing a functional offline experience. The tradeoff is speed: every request incurs network latency even when a cached response is available. This is ideal for API responses and HTML pages where freshness is more important than speed.
Stale While Revalidate (Best of Both Worlds)
Stale-while-revalidate returns the cached response immediately (fast!) and simultaneously fetches an updated version from the network in the background. The next time the user requests the same resource, they get the freshly cached version. This strategy provides instant responses with near-real-time freshness — the content is at most one visit old. It is the best strategy for content pages, blog posts, and any resource where a brief delay in freshness is acceptable. Google's Workbox library recommends this as the default strategy for most web applications.
Precaching: The App Shell Model
Precaching downloads and caches specified resources during the service worker's install event, before the user requests them. This ensures that your core application files (HTML shell, CSS, JavaScript, critical images) are available offline from the very first visit. The precache list should include everything needed to render the basic page structure — the "app shell" — without any network requests.
Keep the precache list small. Every file in the precache list is downloaded during service worker installation, which happens on the user's first visit. A precache list of 500KB feels instant. A list of 5MB causes a noticeable delay and wastes bandwidth for users who may never visit all the precached pages. Focus on the critical path: your HTML shell, main CSS bundle, main JS bundle, and an offline fallback page. Cache other resources on-demand using runtime caching strategies.
Common Pitfalls
Caching HTML with cache-first: If you cache your HTML pages with a cache-first strategy, users will see stale content indefinitely. Use network-first or stale-while-revalidate for HTML pages. Reserve cache-first for versioned static assets.
Forgetting cache busting: When you update your CSS or JS, the service worker serves the old cached version. Use filename hashing (style.a1b2c3.css) or update the cache version name in your service worker to force re-downloads.
Not handling service worker updates: When you deploy a new service worker, it installs but waits for all existing tabs to close before activating. Users on long-lived tabs may run outdated code for hours. Implement an update notification that prompts users to reload, or use skipWaiting() with clients.claim() for immediate activation (but be aware this can cause inconsistencies if the page's cached HTML expects old JS).
Caching error responses: Always check response.ok before caching. Without this check, a 404 or 500 error response gets cached, and the service worker keeps serving the error even after the server is fixed. Only cache responses with status 200.
Frequently Asked Questions
What is a service worker and what does it do?
A service worker is a background JavaScript thread that intercepts network requests, enabling offline functionality, caching strategies, push notifications, and background sync. It is the foundation of Progressive Web Apps.
What caching strategy should I use?
Cache-first for static assets, network-first for APIs, stale-while-revalidate for content pages. Most apps use a combination of all three based on content type.
How do I make my website work offline?
Register a service worker, precache your app shell (HTML, CSS, JS), implement a cache-first or stale-while-revalidate strategy, and create an offline fallback page.
Do service workers affect SEO?
Not negatively when implemented correctly. Googlebot fetches with a cold cache. Use network-first for HTML to ensure crawlers get fresh content. Service workers improve repeat-visit performance.
What is the difference between service workers and web workers?
Service workers are network proxies that persist across page loads. Web workers run CPU tasks off the main thread and die when the page closes. Both run on background threads.