What is Service Worker:
A service worker is a script that runs independently in the browser background. On the user side, it can intercept its network requests and decide what to load (fetch).
Service workers mainly serve features like background sync, push notifications and they are commonly used for’offline first’ applications, giving the developers the opportunity to take complete control over the user experience.
Before it’s time there has been API called AppCache, which has been trying to serve the offline experience feature. However, there have been numerous problems in the interface of the AppCache API and Service Workers are here, going over them.
The service worker life cycle:
During installation, the service worker can cache some static assets like web pages. If the browser cache the files successfully, the service worker gets installed.
Afterward, the worker needs to be activated. During activation the service worker can manage and decide what to happen to the old caches, typically they are being deleted and replaced with the new versions.
Lastly, after activation, the service worker takes control over all pages in his scope, without the page which initially registered the service worker, which needs to be refreshed. The service worker is smart in terms of memory usage and will be terminated if there is nothing to fetch and there are no message events occurring.
Below is a picture of the place of a service worker between the browser and the network.
- HTTPS unless on localhost
- Browser support
- Service Workers are highly supported over the internet by Chrome, Firefox, Opera, Safari and Edge, which makes them worthy for deployment.
After the service worker gets registered it needs to be installed, this is done in the service worker file and where you typically want to fetch your cache assets.
The following steps need to be taken:
- Open a cache
- Cache the assets
- Confirm if the caching is successful
Once the service worker is set up, it should start to interact and use the cached responses. When a particular user navigates through the web pages, the service worker begins to receive fetch events. The following example demonstrates a case when the worker receives a fetch event and search for a matching cache if there is one, it returns the cached file/value, otherwise, it returns the default response of the call to fetch
Service Worker can’t:‘
However, the Service Worker can:
Common use cases: