How Service Workers Work, Visualized - Mullin Stack
Better code – Better human
Better code – Better human

How Service Workers Work, Visualized

service-workers-works

Probably, most of you have heard in one way or another about the new kid in the JavaScript ecosystem. I am talking about Service Workers which are a key part of modern web development. They have gained traction in recent years, all of that thanks to the popularity of progressive web apps, or PWAs.

The big question I had when I heard about this was: “When should we use services workers? Under which scenarios or contexts we can apply them?”

Throughout this post, we will see a few practical cases where they fit and will do a great job for the good of our end-users. The final idea is to have them really happy, right?.

Having said that and before jumping into that practical cases, I think it is a good idea to walk through some fundamentals about services workers. For newcomers, this will be a good bottom-line, in honor to them, let’s put in into a table.

 

What Is a Service Worker?

A service worker is essentially a script that your browser runs in the background. Keep in mind that it is completely independent of the web page that it is working on or serving.

Actually, they act as proxy servers that sit between web applications, the browser, and the network. Any doubt so far? I hope not.

Service workers give web applications the power to work like native apps.



Facts to Take Into Account About Service Workers

  • They can not directly access the DOM. It uses a mechanism by responding to messages sent via the postMessage interface.
  • Terminated when not being used. This means that they are event-driven.
  • Make use of ES6 promises.
  • Because they are so powerful, they need to be used only through HTTPS unless, on the localhost, you can use them without HTTPS. However, if you upload to a remote server they will need HTTPS installed.

How Do Service Workers Work? At a Glance

Basically, they give the ability to applications to intercept network requests, cache those requests to enhance the app’s performance. And that enhancement is because you have already cached all the content.

However, “a picture is worth a thousand words”, so, for a better understanding, let’s see the next image.

How Service Workers work — By the author

The Service Worker Life Cycle

As I mentioned earlier, a service worker works independently from the page it controls. If you want to install a service worker in your web app, the first thing to do is register it.

Once done, the browser that starts the service worker installation steps into the background. Let’s take a look a the next image for a better understanding.

The service worker’s life cycle — By the author

Most Common Use Cases

Now that we have a better understanding of how service workers work, it’s the right time to walk through the most common uses of them.

Cache support

Service workers can be used under a series of cache strategies. So, about those cache strategies, there are the following use cases:

  • Cache only — You have static content that never changes.
  • Network or cache — If you want to show the user the most up-to-date content with the only condition/desire that you want to load it faster.
  • Cache and update — You want to instantly show content and you don’t mind being temporarily out of sync with the server.
  • Cache, update, and refresh — You want to instantly show content while retrieving new content in the background. Once the new content is available, you want to show it somehow.

Web push

Web push allows the application to send push notifications and then brings back the content once a notification is received.

  • Push and retrieve payload — You want to deliver and bring back the content when it arrives.
  • Push payload — You want to deliver not just text but also different kinds of payloads, making your message rich.
  • Push rich — You want to show an image, a vibration, and anything else that enriches the message you want to deliver.
  • Push clients — You want to show different notifications based on the app’s state.

More Complex Use Cases

API analytics

I have a web app. So, I want to add the ability to track its usage and use the sync API to upload gathered data from time-to-time.

Load balancer

You want to dynamically select the best content provider according to server availability. In this case, you need a service worker to intercepts the request to the resources and choose the most appropriate content provider based on its availability.

I highly recommend you check out the whole collection, practical examples, and much more on how to use services workers on ServiceWorke.rs.



Master Your Craft by Getting Your Hands Dirty

As I always say: “Jump in the water and see if you are able to swim.” Reading this post is good and fun but the real diversion starts when you dirty your fingers.

Registering service worker

If we take a quick reminder about one of the pictures above that describes the service worker’s lifecycle, the first thing to do is to install it. To do that, it requires the step of registering it.

Now, you can check that all service workers are running (Chrome inspect image) by going to Chrome://inspect/#service-workers.

Chrome Inspect — Service Workers

Also, if you open the Chrome Developer tool and go to the Application tab -> Service Workers, you will see all the information about the service worker’s state.

Installing it

The most basic example we need to do is cache all files. Also, you can define which files you want to cache. So, the install step is where we can handle that.

Installing service worker

In the code above, what we did is:

  1. Define a name for our cache (mullinstack.com-v1).
  2. Define which files we want to cache. We defined an array.
  3. Inside of the install eventListener, we are saying to the browser to wait until the promise is resolved, and inside that function, we opened a cache that will be stored under the name mullinstack.com-v1.
  4. Finally, we add all the files we defined before to the cache.

Removing all unwanted caches

Now, we need to remove all the old version caches we don’t need.

Unwanted cache

Returning response

Nothing of the above really matters if we are not able to return the cached content. So, you probably want to return one of your cached responses, right?

That is possible inside of the fetch event, which we are going to create right now.

Returning response from cached content

Complete code

https://codesandbox.io/s/service-workers-5twws

Thanks for reading! I hope this post turned out helpful for you.

Leave a comment

Your email address will not be published.