Home  Web-development   Service wor ...

Service workers API example

Service Workers are a key feature of Progressive Web Apps (PWAs). They act as a proxy between the web browser and the network, allowing developers to intercept network requests, cache resources, and provide offline experiences.

How Service Workers Work

  1. Registration:

    • A service worker is registered with the browser. This is typically done from the main JavaScript file of your web application.
  2. Installation:

    • Once registered, the browser attempts to install the service worker. During this phase, you can cache assets for offline use.
  3. Activation:

    • After installation, the service worker moves to the activation phase. This is where you can clean up old caches and perform any necessary updates.
  4. Interception:

    • The service worker can intercept network requests made by your web application and decide how to handle them (e.g., serve from cache, fetch from network).

Example: Registering and Installing a Service Worker

1. Registering the Service Worker

In your main JavaScript file (e.g., main.js):

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

2. Creating the Service Worker

Create a file named service-worker.js:

const CACHE_NAME = 'my-cache-v1';
const urlsToCache = [
  '/',
  '/styles/main.css',
  '/scripts/main.js',
  '/images/logo.png'
];

// Installation: Cache resources
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

// Activation: Clean up old caches
self.addEventListener('activate', event => {
  const cacheWhitelist = [CACHE_NAME];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (!cacheWhitelist.includes(cacheName)) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

// Fetch: Serve cached content if available, else fetch from network
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        // Cache hit - return response
        if (response) {
          return response;
        }
        return fetch(event.request);
      })
  );
});

Explanation:

Registration

Installation

Activation

Fetch Interception

Published on: Jul 25, 2024, 02:28 AM  
 

Comments

Add your comment