# Service Workers and offline support — Web Performance Optimization

Source: https://www.skillbyai.com/en/web-performance/web-perf-20

> 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

**Quiz:** What is Cache First strategy?

- [x] 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.
