Progressive Web Apps

PWA Service Worker for Dummies

The fact of the matter is that service worker has an important role to play in the coming years, and the faster that you can familiarize yourself with this new technology, the better that you can adjust yourself to this new future of the Web. 

This is why that, in order to help you get to know this new technology better, together we will have a discussion about service workers—what it is, what it brings to the Web, how we can better prepare ourselves for this new technology of the Web.

What is a service worker?

Definitions

Universally regarded as the technology that makes or breaks PWAs, service worker is an API that runs independent of the browser and responsible for network interception—and because of this, it can do many of the things that were previously impossible on the Web. Websites (typically PWAs) controlled by service workers can have a deeper integration with the device in use and consequently, bringing more hardware capabilities and app-like features to the Web (e.g. push notifications, background sync, and more).

How it works

In a nutshell. service worker is essentially a event-based layer between the browser and the server that intercepts, modifies, and handles outgoing network requests:

How service worker works

And since service worker is that of an event-based one, it responds to and communicates only through events, and uses promises to tell when an operation is complete. However, all the receiving of events (e.g. fetch and push) are only possible when the service worker is active, which indicates when the browser recognizes and registers the service worker (and also when the service worker itself has successfully finished installing). In a simplified way, this is the typical lifecycle of a service worker:

Service Worker Lifecycle

Also, take note of all these available events in service worker:

Service Worker Events
Summary of available service worker event [Source: Mozilla]

All the functional events (fetch, sync, and push) should be self-explanatory to you, as they’re the events that make for almost all of the progressive features characteristics of PWA (i.e. offline capabilities, background sync, push notifications).

Recommended reading: What Is PWA? All You Need to Know About Progressive Web Apps

Constraints to service workers

Since this is a script that runs independent of the browser, there are some constraints to it:

  • HTTPS protocol: service workers must be run on HTTPS-based websites
  • No access to localStorage, DOM, and the window.
  • Limited scope: service workers can only operate in the scope of the current directory (and sub-directories) that the service-worker.js is located in.
  • Asynchronous: service workers are asynchronous in nature, thus relying Promise-based APIs.

What service workers mean for PWA

As previously stated, service worker is the backbone of PWA, without which many of the revolutionary features of PWA are just not possible. Essentially, what service worker does is it provides the means for:

Better Performance

Performance on repeated visits is significantly better on a PWA, as service workers do tremendously to help with the caching process. Compared to the typical web cache (HTTP cache) used in the majority of websites, PWA excels in serving content even in non-favorable network conditions:

Average page load times comparison

This is all thanks to the fact that service workers give developers total freedom to exactly what and how caching is done. To see just how much better is the caching performance of service workers, we recommend Google’s recent study: Measuring the Real-world Performance Impact of Service Workers. The study has a clear methodology, centered around time to first paint as a metric to determine service worker performance.

On average, pages loaded quite a bit faster when a service worker was controlling the page than they did without a service worker, for both new and returning visitors.

Philip Walton, Measuring the Real-world Performance Impact of Service Workers

Offline Access

When registered, service workers cache the necessary content for your PWA site and serve it afterward. This effectively makes PWA-powered websites offline-capable, as users can still interact with the site and see all the cached content.

View content even when you’re offline with service worker

This is not to say that offline access is a feature previously unseen on the Web either — it was possible to give users an offline experience on the web, it’s just that the experience wasn’t optimal (see Application Cache is a Douchebag) and service workers were invented to address (or more like, avoid) the drawbacks of AppCache

Recommended reading: How to make your PWA work offline

Native app features

Besides offering offline access and improved performance, service workers also serve as the base for more app-like features such as push notifications and background sync (and in the near future, geofencing and periodic sync). The push notifications feature of PWA, for example, is assembled using two APIs: the Notifications API and the Push API, both of which are built on top of the Service Worker API.

Lifecycle of a service worker

The lifespan of a service consists of three parts: registration, installation, and activation, all of which we’ll be going into the details below:

Registration

The first step we need to do is to register the service worker. Without this step, the browser won’t know where your service worker is located and thus, making it impossible to install the service worker in the background.
We can register the service worker using the following code:

if('serviceWorker' in navigator) {
    navigator.serviceWorker.register('./pwa-examples/simicart/sw.js', {scope: './sw-scope/'})
.then((reg) => {
   // registration worked
       console.log('Registration succeeded. Scope is ' + reg.scope);
};

The above code will first start looking for the Service Worker API in the browser and, if the browser supports said API, it registers a new service worker using the serviceworkerContainer.register() method, and gives a scope of the service worker.  For example, in the above code, our scope is /pwa-examples/simicart/ which means our service worker would only work for pages that start with /pwa-examples/simicart/. We call these pages ‘controlled pages’.

Installation

Now that the browser knows where our service worker is — and what’s the scope of it — it will attempt to install the service worker. You can choose to do nothing during this phase but we’d still like to note that this is the phase where most of the caching process happens.  For example, this is typically how the process of caching asset is done:

const cacheName = 'site-cache-v1'
const assetsToCache = [
    '/pwa-examples/',
    '/pwa-examples/index.html',
    '/pwa-examples/css/styles.css',
    '/pwa-examples/js/app.js',
]

self.addEventListener('install', ( event ) => {
    event.waitUntil(  
        caches.open(cacheName).then((cache) => {
              return cache.addAll(assetsToCache);
        })
      );
});

As you can see in the above example, we use the Cache API to cache our assets which we will later use to make our PWA offline-capable. This caching process happens during the install event.

Activation

After the installation stage, we can now activate the service worker. However, this activation stage does not normally happen automatically, and in order for the service worker to activate, you must ensure that there is no service worker currently controlling the pages.

Alternatively, you can also automate the activation process of your service worker by using the skipWaiting() method.

const cacheName = 'site-cache-v1'
const assetsToCache = [
    '/pwa-examples/',
    ‘/pwa-examples/index.html',
    '/pwa-examples/css/styles.css',
    '//pwa-examples/js/app.js',
]
self.addEventListener('install', ( event ) => {
    self.skipWaiting(); // skip waiting
    event.waitUntil(  
        caches.open(cacheName).then((cache) => {
              return cache.addAll(assetsToCache);
        })
      );
});

The web needs service worker

At this point, we can all agree that service worker is almost an eventual step that the Web must take. Users are becoming increasingly demanding of app-like features, and combined the fact that PWA is becoming the future of software delivery, it looks like the Web has a lot of potential in the coming years.

For Magento merchants looking to transform storefront, we provide a cost-effective and complete headless PWA solution for your business.

Luke Vu

A content writer with a passion for the English language.