Lesson 20 / 25
Service Workers and offline support
Implement Service Workers for offline support, instant loading, and improved resilience.
Service Worker lifecycle and registration
Register with navigator.serviceWorker.register(). Lifecycle: install (cache assets), activate (clean old cache), fetch (intercept requests). Supports offline with cached responses, instant repeat visits with cache-first strategy.
Caching strategies with Service Workers
Cache First: return cache if available, fallback to network. Network First: try network, fallback to cache. Stale-While-Revalidate: serve cache immediately, update in background. Choose strategy per resource type.
Service Worker best practices
Scope carefully to avoid unexpected behaviour. Version your caches so deployments can update them cleanly. Monitor updates in analytics. Test offline mode regularly.
Quick check
Quick check: What is Cache First strategy?
- Return cache if available, fallback to network
- Always fetch from network first
- Disable caching
- Always show a blank page offline
Answer
Return cache if available, fallback to network — Cache First serves stored responses instantly and only goes to the network on a miss.