codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

“Work It” featuring Service Workers

--

Service Workers are gaining some serious traction and their role in Progressive Web Apps is a crucial one. More often than not I find developers do not understand Service Workers and can be intimidated by their initial complexity. I have composed this article with high hopes of helping those who are learning Service Workers by discussing their lifecycles and some practical examples of them. Unfortunately Missy Elliot could not contribute to this article.

What the hell is a Service Worker?!

A Service Worker is just a javascript file that runs in the background.

Although that can be considered an over simplification, it starts us off nicely. Service Workers are downloaded and registered in the browser, where they will simply run in the background. A Service Worker runs on a separate thread than the main thread and gives us the awesome ability to reduce the workload on our main thread. Service Workers are shared between tabs.

Why?!

Service Workers seem cool but why would I want to use them?! Well right now there are some really cool ways to use Service Workers like running parallel tasks on a separate thread, offline capabilities, Webpush, and Background Sync to name a few.

Caveats

Service Workers are not without ‘gotcha’s. First, you must run Service Workers on HTTPS in production. Now you can develop on HTTP but as soon as you launch to a domain other than localhost your Service Worker will not register on HTTP. Second, the browser is your judge, jury, and executioner. For the most part it decides when it wants to kill Service Workers and activate new ones in its place. Because of this, we work to write Service Workers that can understand they are picking up where another one may have left off. We are also very careful in the code we write for a Service Worker. We cannot rely on the Service Worker to always be there so we must use it more as a helper rather than a necessary tool. Third, you have absolutely no access to the DOM, localStorage, and Cookies. Fourth, it is important to realize Service Workers are very new and are in a very early stage of support. See the graph below of which browsers support Service Workers.

Service Worker Lifecycles

Service Workers have lifecycles. Each lifecycle has three main events: Download, Install, and Activate. These lifecycles are important opportunities to initialize and stabilize your Service Worker in its environment and sometimes pick up where another Service Worker may have left off.

Download

This event is self explanatory in the fact that we need to download our Service Worker code. Usually this is a specific javascript file we deliver with our application and by registering it with the browser, we can start the download process. Your registration code to kick off the download should look something like this:

Install

After download is complete, your browser will begin to install. Service Workers have a global event for this process that gives you the opportunity to complete almost any task you wish. At this point, your Service Worker is still not active and running but rather initializing itself and getting ready to be utilized by your application. In the Service Worker file you will have an event listener that looks something like this:

Activate

Just like the install event happened after download, our activate event happens after install. This is by far the most important event as this is the starting point of our Service Worker becoming alive.

Putting This Together

When you follow these steps you will see console logs like this:

Debugging

Anyone that has worked with Service Workers enough knows that debugging them may take some years off of your life. It is important to understand the lifecycles of these Service Workers, and to find out which version of the Service Worker your browser has activated.

Update On Reload

This checkbox is your bread and butter in development. It updates your Service Worker on refresh. If this fails or you have trust problems like me, you can simply click ‘Unregister’ on the right side and it will kill your Service Worker. On subsequent reload you will activate a new service worker.

Failed Installs

To see true debugging of the Service Worker when it fails to install, google documentation states that chrome://serviceworker-internals is the best place to visit. Note that other areas of Chrome DevTools may not give you everything you need.

Some Cool Examples

This article would be of little value without some cool examples. Service Workers have infinite uses, but the main use is a local proxy for your network requests. With this proxy sitting between all outgoing calls, you can write condition logic to ‘do things’ if the network fails or is too slow.

Offline Capabilities

Enter Service Workers with the Cache API. The Cache API is a key-value storage for Requests and Responses. We can use a Service Worker to intercept all outgoing network requests using the Fetch API and build ourselves a nice little local cache for the user. In the case of a failed network request and a valid cache entry, we could still have a functional app when dealing with intermittent internet connections. A diagram of this would look something like this:

By using the global event listener below, we can decide what we want to do with each fetch request.

Background Sync

Background Sync is something that the internet has needed for some time now. It is the idea that we can hold on to new values or post requests when we do not have a valid network connection and when we reconnect, attempt to sync these values up to our server. This is incredibly invaluable when building an app that will not break during intermittent lapses in network connection. It lets the user continue to use your application and gives a more native mobile app feel. Twilio had a great GIF of an app sending a test message through background sync after reconnecting.

By using the global event listener below, we can decide what we want to do with each sync event.

WebPush and Notifications

Umm…yeah, Push Notifications for the browser. Cool! WebPush is a great implementation and perfect for communicating via Service Workers. It keeps your main app simple and when the time comes to display a notification, the Service Worker is there for that too! Communication to the Notification API from your Service Worker is possible in both Chrome and Firefox.

By using the global event listener below, we can decide what we want to do with each push event.

Conclusion

Service Workers are cool and hopefully not as intimidating as they were before this article. Google documentation is pretty awesome for Service Workers so check them out. For a demo you can play around with check out my repository.

Related Content

I also did a short talk on Service Workers at SacJS so please check it out!

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

No responses yet

Write a response