We are thrilled to inform you that Lancecourse is becoming INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 91 – Introduction to Service Workers

What are Service Workers?

A Service Worker is a script that runs in the background, separate from your web page.
It acts as a middleman between the browser and the network, allowing you to:

  • Intercept network requests
  • Manage caching for offline experiences
  • Deliver push notifications
  • Handle background sync

Key Characteristics:

  • Runs independently from the web page.
  • Doesn’t have direct access to the DOM.
  • Works with HTTPS only (except on localhost during development).

How Service Workers Work

  1. Registration: Your web app tells the browser there’s a service worker.
  2. Installation: Browser installs the service worker.
  3. Activation: Browser activates the new worker and removes old ones.
  4. Fetching: Service worker can intercept requests and serve cached responses.

Basic Example

// Registering a Service Worker
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js')
    .then(registration => {
      console.log('Service Worker registered with scope:', registration.scope);
    })
    .catch(error => {
      console.log('Service Worker registration failed:', error);
    });
}

Basic service-worker.js Example

// Install event
self.addEventListener('install', (event) => {
  console.log('Service Worker installing.');
});

// Activate event
self.addEventListener('activate', (event) => {
  console.log('Service Worker activated.');
});

// Fetch event
self.addEventListener('fetch', (event) => {
  console.log('Fetch intercepted for:', event.request.url);
});

Why Service Workers Matter

  • Offline Availability: Enable your site to work without a network.
  • Performance Boost: Serve cached files faster than network files.
  • Push Notifications: Send updates even when the app isn’t open.
  • Background Sync: Sync data when connectivity is restored.

Key Events in a Service Worker:

Event Purpose
install Cache assets needed for offline use
activate Clean up old caches, take control
fetch Intercept network requests
sync Sync data when connectivity returns
push Handle push notifications

In Summary

  • Service Workers are powerful background scripts.
  • You must register them in your main JavaScript file.
  • They can intercept and handle network requests.
  • They're crucial for building Progressive Web Apps (PWAs).