Service Worker

A script that runs in the background, separate from a web page, enabling features like offline functionality, push notifications, and background sync.

Overview

Service Workers are a type of web worker that acts as a proxy between the browser and the network. They enable Progressive Web Apps (PWAs) by providing offline capabilities, caching strategies, and background synchronization. Service Workers intercept network requests and can serve cached responses, making your web app work offline.

Example

javascript
// Register service worker (in main script)
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js')
    .then(registration => {
      console.log('Service Worker registered:', registration);
    })
    .catch(error => {
      console.error('Registration failed:', error);
    });
}

// service-worker.js
const CACHE_NAME = 'my-app-v1';
const urlsToCache = [
  '/',
  '/styles/main.css',
  '/script/main.js',
  '/images/logo.png'
];

// Install event - cache files
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => cache.addAll(urlsToCache))
  );
});

// Fetch event - serve from cache
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => response || fetch(event.request))
  );
});

// Activate event - clean old caches
self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheName !== CACHE_NAME) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

Key Points

  • Runs in background, separate from page
  • Enables offline functionality
  • Required for PWAs
  • Intercepts network requests
  • Requires HTTPS (except localhost)

Learn More