Service Worker Generator
Configure and generate a service worker with caching strategies, precaching, and offline support.
Caching Strategy
A unique identifier for this cache version. Change it (e.g. "v1" to "v2") when you deploy updates to force the service worker to refresh cached assets.
These URLs are fetched and cached during the service worker install step, making them available offline immediately. List your app shell, key pages, and critical assets.
A page to show when a request fails and no cached version exists. Typically a simple "You are offline" page. Leave empty to disable.
Lifecycle Options
Control how quickly a new service worker takes over from the previous version. Enabling both ensures updates activate instantly across all open tabs.
Generated Service Worker
const CACHE_NAME = 'v1';
const PRECACHE_URLS = [
'/',
'/index.html',
'/styles.css',
'/script.js',
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(PRECACHE_URLS);
})
);
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames
.filter((name) => name !== CACHE_NAME)
.map((name) => caches.delete(name))
);
})
);
self.clients.claim();
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((cached) => {
return cached || fetch(event.request);
})
);
});Registration Snippet
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then((reg) => console.log('SW registered:', reg.scope))
.catch((err) => console.error('SW registration failed:', err));
});
}
</script>What is a Service Worker?
A service worker is a JavaScript file that runs in the background of your web application, separate from the main browser thread. It acts as a programmable network proxy, intercepting requests and deciding how to respond — from cache, from the network, or a combination of both. This enables features like offline support, background sync, and push notifications.
Service workers are a core building block of Progressive Web Apps (PWAs). They follow a lifecycle of installation, activation, and fetch handling, giving you fine-grained control over how your application behaves when the network is slow, unreliable, or completely unavailable.
How to Use This Service Worker
- 1. Configure your options — Choose a caching strategy, set a cache name, and list the URLs you want to precache. Toggle Skip Waiting and Clients Claim based on your update strategy.
- 2. Download or copy the generated code — Save the generated JavaScript as
sw.jsin the root of your web project (or your public/static folder). - 3. Add the registration snippet — Copy the HTML registration snippet into your
index.htmlor main layout file. This tells the browser to install your service worker. - 4. Test in the browser — Open DevTools → Application → Service Workers to verify it is registered and active. Check the Cache Storage section to confirm your precached URLs.
Caching Strategies Explained
- Cache First
- The service worker checks the cache before making a network request. If a cached response exists, it is returned immediately. If not, the request goes to the network. This is ideal for static assets like images, fonts, and CSS files that rarely change.
- Network First
- The service worker always tries the network first. If the request succeeds, the response is cached for future use. If the network fails, the cached version is served as a fallback. This works best for API calls and pages with frequently changing content.
- Stale While Revalidate
- The service worker returns the cached version immediately (if available) while simultaneously fetching an updated version from the network. The next request will get the fresh response. This provides the speed of cache-first with the freshness of network-first — great for news feeds, social timelines, and dashboards.
Frequently Asked Questions
- What does Skip Waiting do?
- By default, a new service worker waits until all tabs using the old version are
closed before activating. Calling
skipWaiting()forces the new worker to activate immediately, replacing the old one. Enable this for faster updates, but be aware it can serve a mix of old and new assets in the same session. - What does Clients Claim do?
- When
clients.claim()is called in the activate event, the service worker takes control of all open pages immediately — even those that were loaded before the worker was installed. Without it, the worker only controls pages opened after installation. - Do I need HTTPS?
- Yes. Browsers require HTTPS to register a service worker (except on
localhostfor development). This is a security measure since service workers can intercept every network request from your page. - How do I update my service worker?
- Change the cache name (e.g., from "v1" to "v2") and update your precache list. The browser detects byte-level changes in the service worker file and triggers the install/activate lifecycle again, clearing old caches in the process.
- Can I use different strategies for different routes?
- Yes, but that requires a more advanced setup. This generator produces a single-strategy service worker for simplicity. For route-based strategies, consider libraries like Workbox that provide a higher-level API for composing multiple caching rules.