67. What is a service worker in JavaScript?
medium

A service worker is a script that runs in the background of a web application, providing caching and offline capabilities. It is designed to perform tasks asynchronously and efficiently, without blocking the main thread of the browser or affecting the user interface.


In JavaScript, a service worker can be registered using the navigator.serviceWorker.register() method. Once registered, the service worker can listen for events such as fetch and install, which allow it to intercept requests and cache responses. This caching capability allows the application to continue functioning offline, without requiring an internet connection.

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js')
      .then(registration => 
        console.log('Service worker registered:', registration))
      .catch(error => 
        console.error('Error registering service worker:', error));
  });
} else {
  console.log('Service workers are not supported in this browser.');
}

Once a service worker is registered, it can listen for the fetch event and cache responses using the addEventListener() method:

self.addEventListener('fetch', event => {
  const response = event.request;
  event.respondWith(cacheResponseOrFetch(response));
});

async function cacheResponseOrFetch(response) {
  // Check if the response is in the cache
  const cachedResponse = await caches.match(response);
  
  // If the response is in the cache, return it
  if (cachedResponse) {
    return cachedResponse;
  }
  
  // Otherwise, fetch the response and cache it for future use
  const fetchResponse = await fetch(response);
  await caches.open().then(cache => cache.add(response));
  return fetchResponse;
}

This example shows a service worker that listens for the fetch event and caches responses using the caches.match() and caches.add() methods. The cacheResponseOrFetch() function checks if the response is already in the cache, and if not, fetches it using the fetch() method and adds it to the cache for future use.


Overall, service workers are a powerful tool in JavaScript that allow web applications to provide caching and offline capabilities without affecting the user interface or requiring an internet connection.