DEV Community

Cover image for JavaScript Service Workers, Visualized
Roberto Hernandez
Roberto Hernandez

Posted on

JavaScript Service Workers, Visualized

Originally published on Medium

Probably, most of you have heard in one way or another about the new kid in the JavaScript ecosystem. I am talking about Services 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 blarz<br>

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.

Service Workers Life Cycle work — By blarz<br>

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.

Registering Service Worker

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

Chrome Inspector

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.

Chrome Inspector

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.

Removing all unwanted caches

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<br>

Complete code

Thanks for reading! If this story turned out to be interesting, I’d really appreciate it if you share it with your friends.

Feel free to reach me on my blog and Medium

Latest comments (3)

Collapse
 
faqndo97 profile image
Facundo Espinosa

hey! Great post! I really liked the diagrams that you added, which tool did you use?

Collapse
 
icalrn profile image
Faisal Rahman

Such a concise yet comprehensive article on service workers!

I have one question though. What will happen if the service worker intercepts a request from the browser and forwarded the request to the server, but before the request gets fulfilled, the browser navigates away from the page that made the request? Without service workers, the request would be canceled by the browser AFAIK. What will the service worker do in such cases?

Collapse
 
marcotraspel profile image
Marco Traspel

Looks like a nice comprehensive post! Thanks, gonna read it later! #ServiceWorkerFamily :D