Service Workers

What are service workers, what can we do with them, what problems do they solve, what is their life cycle and how to register a service worker on a website.

In this article we are going to address one of the biggest utilities that has emerged in the world of web development in this decade, the service worker. Without a doubt it is, and will be, one of the main protagonists of the next web revolution.

Before service workers, traditional Web applications were limited in their use when they were open in a browser tab. In the Mobile world, a similar thing happens, since traditionally they only respond if we are visiting the page at a given moment.

However, thanks to Progressive Web Apps, this limitation no longer exists, so that a web application can behave the same as a Mobile App, which, even when closed, can continue to interact with the user, such as through Push Notifications.

What is a Service Worker?

Service workers make sense in many scenarios, but basically they allow us to keep a website running in the background. They basically consist of a script (Javascript file) that continues its execution, regardless of whether a web page is open or not.

Some interesting things about Service Workers:

  • A Service Worker cannot directly access the DOM, the Service Worker communicates with the pages it controls through the PostMessage interface.
  • With a Service Worker you can control how network requests are handled
  • They are capable of implementing various caching systems.
  • They can persist information through the indexedDB.

What do I need to use Service Workers?

Browser Support

Obviously, you can only use a service worker if the browser allows you to register it. Most of the browsers have implemented it and the rest have already declared their support for the technology and their support is under development. You can see current support here.

HTTPS:

The website needs to be delivered using a secure protocol in order for the Service Worker to be registered.

Note: In the development phase you do not have a secure server. That’s not a problem, since http://localhost is considered a secure server, even though it isn’t. If you enter your server by “localhost” the service worker will be able to register. If you do it through the loop IP, or the IP of a server, it cannot be taken into account as a secure server, unless you are actually in https.

Understanding the life cycle of service workers

Service workers have a life cycle independent of the Web. Understanding the Service Worker life cycle will lead to delivering an excellent experience to our users.

Font:

I will now summarize the states.

Install: This is the first event that occurs. Occurs only once per Service Worker. If the promise you call in this event fails, the browser doesn’t log it and doesn’t let the Service Worker take control of the client.

Activate: Once the Service Worker is controlling the client and is ready to use and handle events, it enters the Activate state. We could understand it as our Service Worker being active.

Terminated, Fetch: Once the Service Worker is in control of the pages, it can be in one of these two states. Terminated is applied to save memory. On the other hand, if it is managing network requests, its status will be fetch.

How to add a Service Worker?

The process of adding a service worker to a website is simple, basically creating the file with the script code and then registering it with the register() method of the browser’s service worker API.

1.- Create the Javascript file of your Service Worker

Create a javascript sw.js file and place it at the root of your web project (usually at the same level as index.html).

Note: We’re not looking at service worker script code at this time, a topic that’s covered in more detail later, so you can just leave the sw.js file blank for now. But we already told you that there are services and libraries to be able to generate service worker code in a more or less simple way. We anticipate for the moment this website created by the Google team: .

2.- Register the Service Worker.

The job of registering the service worker requires a bit of Javascript code, which you would have to place like any other script on your page. Registration could be done with a single call to a browser service worker API method, but we need to make sure our client has support for this technology.

You typically use code like this to register the Service Worker:

if (‘serviceWorker’ in navigator) { window.addEventListener(‘load’, function() { navigator.serviceWorker.register(‘/sw.js’).then(function(registration) { // If successful console.log (‘SW registered successfully’); }, function(err) { // If failure console.log(‘SW failed’, err); }); }); }

3.- See the registered service worker

If the browser supports it you should see the service worker registered from your developer tool. In my case I see it from the Chrome Developer Tools.

You have to enter the “Application” tab and then on the left side the “Service Workers” option. In the following image you have a sample of what you will see.

Well congratulations, you’ve now given your site the ability to take advantage of new web features!

If you want to investigate something else, I invite you to enter the Mozilla page and try some strategies to extend your Service Worker.

Service Workers explanation video

Below is a video tutorial, explaining in more detail what service workers offer you and how you can include a new service worker in a progressive application project. You will learn to use Workbox in a general way, one of the libraries available to easily generate the code for service workers.

Until a Next Post 🙂

See also  How to tell if a variable is null in Javascript
Loading Facebook Comments ...
Loading Disqus Comments ...