# Service Workers and offline support — Web Performance Optimization

Source: https://www.geekswithgeeks.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 behavior. Version caches to enable updates. Use self-closing versions for deployments. Monitor updates in analytics. Test offline mode regularly.

Quick check

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

- [ ] Return cache if available, fallback to network
- [ ] Always fetch from network first
- [ ] Disable caching
