What is a Service Worker?


A Service Worker is a script that runs in the background, in a separate thread from the browser UI. Service worker cache makes it possible for a web site to function offline.

They are one of the things that make a web application a progressive web app. They enable platform integrations, like rich caching and push notifications.  

It is an extensible platform and additional features are currently being planned. 

Service workers don’t have access to the DOM, but can intercept all network request.

There are some key features of service workers: 

  • A Service Worker is a JavaScript File 
  • They run on a different thread from the UI 
  • Service worker doesn’t have direct access to the DOM 
  • it only  runs when in use, so no battery strain 
  • They work solely within the origin or domain they are registered with 
  • They require HTTPS 
  • Service workers send messages to and from the UI 
  • They are supported by all major browsers 
  • Are similar to but better than web workers 

How they Work?

A Service worker acts like a proxy server between the browser and the network. They are event driven and live outside the browser process, enabling them to work without an active browser session.  

Service workers are stopped when not in use and restarted when needed, this reduces strain on the CPU and batteries.  

Apart from offline experience, websites can load instantly when retrieved from cache.  

Service Worker Extensibility

Service workers are designed as a backbone that supports additional functionality. Some examples of such features are native push notifications and background sync.  

They also a site is served using HTTPS protocol. This prevents many common attacks.  

Also, they work asynchronously which means processes will not be blocked when they are lots of processes.