JavaScript Service Workers, Visualized
Tags: javascript, beginners, programming, service
Published: 2020-03-06 01:35:29

**Originally published on [Medium](https://medium.com/better-programming/javascript-service-workers-visualized-308ca3292b6a)**


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
](https://miro.medium.com/max/2331/1*pY5oSrjUqZ8Fr4YIKKX_6Q.gif)

# 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
](https://miro.medium.com/max/2331/1*MGS11eUn4T8pCfPuW93ccg.gif)


# 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](https://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](https://miro.medium.com/max/1536/1*RgW-rGFd-DGlfT2Ni07LcQ.png)


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

![Chrome Inspector](https://miro.medium.com/max/2380/1*2uMdB4WobEEsUS-5MVnT5w.gif)

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](https://miro.medium.com/max/2380/1*mZvcEtwn78x6502jsG7dfg.gif)


## 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](https://miro.medium.com/max/1453/1*52dS-ZXMVPI45M8oKz_C2A.png)

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](https://miro.medium.com/max/1325/1*uxYGeBrKP9-FsjF7udTZgA.png)


# 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
](https://miro.medium.com/max/1355/1*erCgeO2hG1Qug7tdkEn2cw.png)

# Complete code

{% codesandbox service-workers-5twws %}





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](www.mullinstack.com) and [Medium](https://medium.com/@blarz)***