How service worker works?

2.1k Views Asked by At

I am newbie to progressive web apps. I have gone through this amazing tutorial and setup for my react PWA(progressive web) app.

Now this is my serviceworker.js file

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    window.location.hostname === '[::1]' ||
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export default function register() {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
    if (publicUrl.origin !== window.location.origin) {
      return;
    }

    window.addEventListener('load', () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        checkValidServiceWorker(swUrl);
        navigator.serviceWorker.ready.then(() => {
        });
      } else {
        registerValidSW(swUrl);
      }
    });
  }
}

function registerValidSW(swUrl) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              console.log('New content is available; please refresh.');
            } else {
              console.log('Content is cached for offline use.');
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

function checkValidServiceWorker(swUrl) {
  fetch(swUrl)
    .then(response => {
      if (
        response.status === 404 ||
        response.headers.get('content-type').indexOf('javascript') === -1
      ) {
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        registerValidSW(swUrl);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.'
      );
    });
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}

But could not able to understand how it works? Can anyone please help what register, unregister and other function do here?

Please help!!!

1

There are 1 best solutions below

1
On BEST ANSWER

Based from the documentation:

A service worker is a type of web worker. It's essentially a JavaScript file that runs separately from the main browser thread, intercepting network requests, caching or retrieving resources from the cache, and delivering push messages.

From your sample code above, you are using react framework to build PWA with create-react-app. It will eliminates all of that by allowing developers to build React apps with little or no build configuration.

To Build a realtime PWA with React:

The service worker code basically registers a service worker for the React app. We first check if the app is being served from localhost via the isLocalhost const value that will either return a truthy or falsy value. The register() function helps to register the service worker to the React app only if its in a production mode and if the browser supports Service workers.

The registerValidSW() function that will register the valid service worker and responsible for the state if it is installed. The checkValidServiceWorker() will check if service worker can be found. This will ensure service worker exists, and that we really are getting a JS file.

The unregister() function helps to unregister the service worker.