Service Worker | Web Fundamentals

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:

  • 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?

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)

--

--

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhay Jain

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