Service Worker | Web Fundamentals

Abhay Jain
2 min readJan 9, 2021

A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction.

Today, they already include features like push notifications and background sync. In the future, service workers might support other things like periodic sync or geofencing. The core feature discussed in this tutorial is the ability to intercept and handle network requests, including programmatically managing a cache of responses.

The reason this is such an exciting API is that it allows you to support offline experiences, giving developers complete control over the experience.

Things to note about a service worker:

  • It is a JavaScript File.
  • They execute on a separate thread from the UI.
  • It can’t access the DOM directly.
  • There is a life cycle or a series of events for a service worker.
  • They are isolated to the origin or domain they are registered with.
  • Service Workers require HTTPS.

Service Workers Work?

A Service worker sits between the browser and the network, acting as a proxy server, handling a collection of non-UI centric tasks. They are event-driven and live outside the browser process, enabling them to work without an active browser session.

The service worker is a script that executes in a thread, separate from the UI. This enables the service worker to perform non-UI tasks, making a web site perform better. Service workers terminate when not in use and restored when required, this keeps them from straining the CPU and draining batteries. Caching not only enables offline experiences, but websites can also load instantly when retrieved from cache. Service worker caching makes the network a progressive enhancement, or not required to make the site usable.

Basic Setup of the Service worker

First, make a Basic Html File and add a script in a file (eg: sw.js).

In the script, check if Browser supports ServiceWorker or not?

Then add a script that does all the stuff you want your service worker to do.

If you want to learn or add more features to the code, you can check the above code. (https://github.com/abhayjain13/service-worker)

--

--

Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.