× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Take Advantage of Service Workers in JavaScript

Since service workers form the basic layer upon which these features can be built, it is important to take technical dive into what constitutes them and also how to implement them.

Basically, a service worker is nothing but a script that is run in the background and by the browser itself. However, it is completely separate from a web page and also offers a host of features that does not rely on the need for a web page. In fact, in today’s terms, we already have seen a number of such implementations such as push notifications, geo-fencing and background syncing.

In this tutorial, we shall discuss the core feature, which involves the interception and handling of network requests. This shall also include the ability to manage a cache of responses programmatically. Also, this is a very exciting API to work with since it allows for offline support and thus gives developers complete support over the complete experience.

Before service workers invaded the landscape, there was another way to achieve offline experience. This was possible by means of the App Cache. However, it has its own issues and also worked better for single page apps and not for sites with multiple pages. Service workers, so far, have taken care of these issues though.

Service worker – Points to note

Here are some points that are noteworthy with respect to service workers.

  • Primarily being a JavaScript worker, a service worker cannot access the DOM directly. However, it can communicate with the pages that it controls by simply responding to messages that are sent by postMessage interface. Also, these messages are capable of manipulating the DOM if need be.
  • Service worker is mainly a network proxy that is programmable. Therefore, it allows you to control the manner in which network requests from your page are handled.
  • They are terminated when their use ceases and also restarted when they come of use. Thus, one cannot rely on the global state of any of service workers onmessage and onstate handlers. If, in case, you have information that might be needed across the various restarts, service workers can access the IndexedDB API.
  • Service workers are known to make an extensive use of JavaScript promises.

The lifecycle of a service worker

As mentioned above, a service worker has a lifecycle that is in every way separate from a web page. In order to make use of a service worker, you will first need to register it to your website. This can be done by registering it in your page’s JavaScript and this allows the browser to start the worker installation step in the background. Generally, during the installation step, one can cache some static assets. If all the files happen to be cached successfully, the service worker stands installed. However, if there is any missing file during the cache, the installation step fails and also does not activate the service worker. In case this happens, do not worry, as it does try to install again the next time.

The installation step in followed by the activation step, where one can handle any of the old caches as well. After this, the service worker takes control over all the web pages that fall under its scope. Note that the page that registered the service worker isn’t controlled until the next time it is loaded.

A service worker will necessarily be in either of two states that it can exist in. One is the active state, where it handles messages and network requests through fetch and message events. The other is the terminated state, when it is not in use to save memory.

Following image is showing the life cycle of service worker

Figure 1. Service worker life cycle

First Steps

One can obtain the caches polyfill from the given repository in GitHub, https://github.com/coonsta/cache-polyfill. You can use this on your site and use a service worker with the importScripts method in it. Any script that is imported is cached automatically by the service worker.


The polyfill adds support for Cache.andAll, which is presently not supported in Chrome M43’s CacheAPI implementation.

HTTPS is a necessity

When it comes to service workers, they are very powerful means that can hijack connections, even fabricate and filter responses. Now, while this might be put to good use by a developer, a hacker certainly won’t.

During development, a localhost may be enough for the use of service workers, but HTTPS is necessary for their deployment in a site. Thus, one can only register for service workers on pages that are served over HTTPS connections. This assures users that they haven’t been tampered with enroute to their browser. GitHub, being setup over HTTPS means that you can use for hosting your demos. If you wish to obtain HTTPS for your site, you will need to get a TLS certificate that needs to be setup on your server. The process can vary and be sure to check your server’s documentation.

Registering a service worker

Now that we have taken care of HTTPS and polyfill, we shall go ahead into the main course of action with the registration and installation of a service worker.

The first step is to register a service worker on your page. This tells the browser the location of your service worker JavaScript files.

Listing 1: Registration of a service worker

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then(function(registration) {
    // Registration was successfully done.
    console.log('ServiceWorker registration successful with its scope: ',    registration.scope);
  }).catch(function(err) {
    // registration for service worker has failed!
    console.log('ServiceWorker registration has failed: ', err);

The given code it meant to check if the API for a service worker is available and if so, the worker at /sw.js is registered.

For checking, you can see if a service worker is enabled by going to chrome://inspect/#service-workers and then looking for your website.

Installation of service worker

After the controlled page that takes care of the registration process, we come to the service worker script that handles the installation part.

Basically, you will need to define a callback for the install event and then decide on the files that you wish to cache. Inside a callback, one needs to take of the following three points –

  • Open a cache
  • Cache the files
  • Seek confirmation for the required caches and whether they have been successful.

Listing 2: Example of service worker installation

var CACHENAME = 'My site’s cache';
var urlstocache = [
self.addEventListener('install', function(event) {
  // Performing installation steps
      .then(function(cache) {
        console.log('Opening of cache');
        return cache.addAll(urlstocache);

The caches.open, along with the cache names can be used for calling and we can also call cache.addAll to pass all the files. This is also basically a chain of promises.

On the successful caching of all the files, the service worker is installed. If not, this particular step fails.

Caching and returning requests – How to do them?

After the installation of a service worker, you might want to return one of the responses. When a user moves away to a different page or even refreshes the page, the worker will receive fetch events like the one given below.

Listing 3: Example to receive fetch events

self.addEventListener('fetch', function(event) {
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        return fetch(event.request);

Here the fetch event has been defined and in the event .respondWith, and from caches.match we pass in a promise. The latter looks for requests and finds cached results from the caches created by the service worker.

If there is a response that matches, the cached value is returned or else the return of a call is made to fetch.

Listing 4: Example to cache new requests cumulatively

self.addEventListener('fetch', function(event) {
      .then(function(response) {
        // Cache hit and return response
        if (response) {
          return response;
        // IMPORTANT NOTE: Cloning the request. A request is a stream and
        // can therefore only be consumed once. However here we are consuming this
        // once by cache and another by the browser for fetch. Thus, it is necessary to clone the response.
        var fetchrequest = event.request.clone();
        return fetch(fetchrequest).then(
          function(response) {
            // Checking for the receipt of a valid response
            if(!response || response.status !== 250 || response.type !== 'basic') {
              return response;
            // IMPORTANT: Cloning the response here. 
            var responsetocache = response.clone();
              .then(function(cache) {
                cache.put(event.request, responsetocache);
            return response;


Service workers have seen more implementation these days and have proven to be more than just useful. As more and more features are required without really affecting the actual web page, service workers help developers live up to these expectations. Some of the features that have been implemented are the likes of syncing in the background and push notifications without making use of native applications to solve the purpose.

The above article is a very basic means to get started with service workers. It covers registration, installing and the returning of responses by using service workers.

Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login