Service Worker Registration and Lifecycle
Register a Service Worker script, understand the install, activate, and fetch lifecycle events, and use skipWaiting and clients.claim.
What Is a Service Worker?
A Service Worker is a JavaScript file that runs in a separate browser worker (not the main thread) and intercepts network requests for your origin. It's the engine behind offline PWAs, push notifications, and background sync.
Registering a Service Worker
Register from your main script. Service workers require HTTPS (except on localhost).
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js', { scope: '/' })
.then(reg => console.log('SW registered:', reg.scope))
.catch(err => console.error('SW registration failed:', err));
});
}All lessons in this course
- The Web App Manifest
- Service Worker Registration and Lifecycle
- Offline Caching Strategies: CacheFirst NetworkFirst
- Push Notifications