What is a service worker

Service workers are at the base of all PWAs, and allow us to intercept network requests and implement the appropriate caching strategy for these calls.


Definition

A service worker is a special kind of web worker, but there is a subtle difference between them:

A service worker is a JavaScript file acting as a proxy between our web application and the network.

Web workers are scripts with a generic purpose, commonly used to lift heavy tasks from the main thread and run them in a different context.

A service worker (in short, SW) can intercept HTTP requests and serve the responses from the network or a local cache, according to which caching strategy you implemented (more details in the next chapter).


We’ll describe the main characteristics:

Secure

Service workers only function on secure connections (HTTPS). This is a safe decision because otherwise, you easily expose your application to man-in-the-middle attacks. Let’s imagine what might happen if anybody could substitute your SW with a manipulated one and be capable of sniffing ALL the network requests… you for sure don’t want that!


On the other hand, the localhost is considered secure, testing the application before deploying it.

⚠️ Note! One extra word about Angular: we cannot use the ng serve command to build and serve our application locally because it doesn’t work with service workers.
In this case, we have to use an HTTP server of our choice, for example, http-server package or the Web Server Chrome extension.


No direct DOM interaction

SW cannot access the DOM directly. They can, however, communicate with the pages under their scope through the postMessage interface. These pages can then manipulate the DOM allowing indirect access.


Non-blocking

Service workers, similarly to web workers, run on an independent thread separate from the one used by our application. Therefore, here, “non-blocking” means that heavy load operations or SW crashes would not affect the performance of our web application in any way.
Their capability of running in the background is also why we can display web notifications to our users, even when they are not actively accessing our web application.


Service worker compatibility

You can verify the browser support for SW by consulting the following links:



Get hands-on with 1200+ tech skills courses.