What is Service Worker?


In this post I ll try to answer, what is service worker and how can we use it?

What is Service Worker?

Old browsers use only main thread to render web pages. Modern browsers now have two main threads available, one for rendering web pages and other running parallel in background. That second thread can execute JavaScript which can perform background tasks like prefetching media or performing offline processing. We call that JavaScript code as a service worker.

How we can use Service Worker?

Service worker can intercept network requests, can modify requests and also can originate new requests to server using fetch API. That means it is a great tool for providing cache.
Service worker can be used for background-sync and displaying push messages as well as pre-fetching images/css/js assets from server.

Service worker can be installed, removed and updated. That is just like we install, reinstall or uninstall some software from our system.

Where can I see Service Worker?

You can use browser web/dev tools to see how service worker is loaded.

If you inspect source you can see the javascript code in the service-worker.js

Important concepts

Service worker can not access DOM because it is a separate thread.

Service worker is fully asynchonous (non blocking), that means localStorage and synchronous XHR can not be used.

Service worker can receive push messages from server and display them in browser notifications even the web app is not opened in the browser.

Service Worker run only over HTTPS because they can intercept network calls and can modify them.

FAQs

How we communicate with the web page?
We can use the postMessage method i.e navigator.serviceWorker.controller.postMessage(data) to send some data from the web app to service worker and in service worker to accept that data we can add message event listener like self.addEventListner(‘message’

How to share data between Service-Worker and a Web page?
Hence Service-worker are async the sync storage like localStorage can not be used to share data, we can use IndexedDB to share data between Service-Worker and web app.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s