The one with the Service Worker

I would like to begin this article with Service Worker – the unicorn, because that’s what it was for me when I first started reading about it. You know, a mythical creature, I was trying so hard not to deal with. But the truth is, it does exist. And for good!

If you are anything like me, then you might still think of service worker as a unicorn. I’m here to help transform that figure into a not-so-mythical creature. Actually, it now is The Dark Knight for me.

WHAT IS A SERVICE WORKER?

A service worker is a script that is run by the browser in the background, for features that don’t need a web page or user interactions. It is extremely powerful; it can be used to intercept network requests made by the user and hijack the connection to fabricate a different response than what was requested. Which means it provides complete control of how your app behaves in certain situations and determines how to respond to requests for resources of your origin. It runs in its own global script context, outside the page. It is event driven in the sense that it can terminate when not in use, and run again when needed.

Service worker includes some features like:

  • Push notifications
  • Background data synchronization
  • Intercepting network request
  • Programmatically managing a cache of response
  • Improving site’s performance

So basically, it works in the background, handling some very powerful stuff and it is here to make our lives better.
To summarize, a service worker is a silent guardian, a watchful protector. A Dark Knight.

Do you see the smooth transition from a unicorn to the Dark Knight? 😉

Also, the really cool part about service workers is that they allow offline experiences, which means that if you load a website once in presence of network, you can reload it while you’re offline.

BEWARE!

Service workers have all these amazing features, but with great power comes great responsibility (and in this case, security). And therefore, the sites registered with a service worker must be served over a secure connection. The good news is, Github pages are served over HTTPS, and that makes them a great place to begin.

Note:
– Since a service worker is essentially a JavaScript worker with no pages linked to it, it cannot access the DOM directly.
– Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same ServiceWorker object.


SERVICE WORKER REGISTRATION

//make sure that Service Workers are supported by your browser.
if (navigator.serviceWorker) {
    navigator.serviceWorker.register('./service-worker.js', {scope: './about'})
        .then(function (registration) {
            console.log('Tadan!', registration);
        })
        .catch(function (error) {
            console.error('Uh-oh!', error);
        })
} else {
    console.log('Service Worker is not supported in this browser.');
}


We first register a service worker to control one or more pages that share the same origin. We can do this by using serviceWorker.registration() method which takes a parameter to tell the browser where the service worker JavaScript file lives (e.g., the path to the script that defines the service worker) and optionally, a second parameter which specifies the scope in which the service worker can operate
.

SERVICE WORKER LIFE-CYCLE

sw-lifecycle
Source of image: MDN

The life cycle of a service worker mainly has three stages:

  • DOWNLOAD
    A service worker is immediately downloaded when a user first accesses a service worker-controlled page. After that it is downloaded at least once every 24 hours.
  • INSTALL
    Installation is attempted when the downloaded file is found to be new. It can either be:
    – The very first service worker encountered by the web page, or
    – A new download, different from the existing service worker. (current worker and the new referenced version are bit-wise compared)
  • ACTIVATE
    – If it is the first service worker encountered by the web page, it is immediately activated after successful installation.
    – If a new version is found, different from the existing service worker, the browser waits (service worker is said to be in a waiting state) to make sure that there are no longer any pages loaded that are still using the old service worker. Once it confirms this, it will activate the new version.

And voilà! We now have an active service worker which can control pages, but only those opened after the registration is successful.
Note: Documents will have to be reloaded to actually be controlled by the service worker if they were open before its registration.

SERVICE WORKER UN-REGISTRATION

To unregister a service worker we can use unregister method of the ServiceWorkerRegistration interface. The service worker will finish any ongoing operations before it is unregistered.

navigator.serviceWorker.getRegistration().then(function(r) { 
  r.unregister();
});


TAKE A LOOK AT ALL THE SERVICE WORKERS

We can look at the dashboard that lists all registered service workers and shared workers in the Firefox browser by going to about:debugging in a new tab and clicking on the Workers tab on the left.
Alternatively, we access this from the Tools -> Web Developer -> Service Workers.

So that’s it! Now that we know a little about service workers, we shall see how they fit in the Web Push movie (starring The Dark Knight) in the next article. Till then, happy coding! 🙂

PS: Life would be infinitely simpler if we were all unicorns.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s