Service Workers Cheat Sheet
Covers registering a service worker, its install and activate lifecycle, caching strategies, and offline-first fetch handling.
2 PagesAdvancedMar 12, 2026
Registering a Service Worker
Feature-detect and register from the main page.
javascript
// main.js — runs in the pageif ('serviceWorker' in navigator) { window.addEventListener('load', async () => { try { const reg = await navigator.serviceWorker.register('/sw.js', { scope: '/' }); console.log('SW registered:', reg.scope); } catch (err) { console.error('SW registration failed:', err); } });}
Install & Activate (Caching)
Pre-cache the app shell and clean up old caches.
javascript
// sw.jsconst CACHE_NAME = 'app-shell-v3';const ASSETS = ['/', '/index.html', '/styles.css', '/app.js'];self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => cache.addAll(ASSETS)) ); self.skipWaiting(); // activate the new SW immediately});self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((keys) => Promise.all( keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key)) ) ) ); self.clients.claim(); // take control of open pages});
Fetch Event (Cache-First Strategy)
Serve from cache, fall back to network, then to an offline page.
javascript
self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((cached) => { if (cached) return cached; // cache-first return fetch(event.request) .then((response) => { const clone = response.clone(); caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone)); return response; }) .catch(() => caches.match('/offline.html')); }) );});
Lifecycle & Concepts
Key events and APIs every service worker uses.
- install- Fires once on registration; typically used to pre-cache the app shell
- activate- Fires when the SW takes control; used to clean up old caches
- fetch- Intercepts every network request from controlled pages, letting you serve from cache
- scope- A SW only controls pages under its registration path
- skipWaiting()- Forces a newly installed SW to activate without waiting for old tabs to close
- Background Sync- Defers actions (like form submits) until connectivity is restored
- Push API- Enables receiving push notifications even when the site tab is closed
Pro Tip
Service Workers require HTTPS (localhost is exempted for development) — always version your cache name (e.g. app-shell-v3) and delete stale caches in the activate handler, or users get stuck on old assets indefinitely.
Was this cheat sheet helpful?
Explore Topics
#ServiceWorkers#ServiceWorkersCheatSheet#WebDevelopment#Advanced#RegisteringAServiceWorker#InstallActivateCaching#Fetch#Event#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance