0Pricing
Frontend Academy · Lesson

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

  1. The Web App Manifest
  2. Service Worker Registration and Lifecycle
  3. Offline Caching Strategies: CacheFirst NetworkFirst
  4. Push Notifications
← Back to Frontend Academy