Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Registering a Service Worker

Web apps follow a specific process to install a service worker; there’s no automatic way to do it today. The app basically executes some JavaScript code to register the service worker with the browser. In the Tip Calculator app in Chapter 1, “Introducing Progressive Web Apps,” I added the code to do this directly in the app’s index.html file. For the PWA News app, we use a different approach.

In this section, you’ll modify the project’s existing public/index.html file plus add two JavaScript files: public/js/sw-reg.js and public/sw.js.

In the <head> section of the project’s public/index.html file, add the following code:

<!-- Register the service worker -->
<script src='js/sw-reg.js'></script>

This tells the web app to load a JavaScript file that registers the service worker for us. Next, let’s create that file. Create a new file called public/js/sw-reg.js and populate the file with the code shown in Listing 3.2.

Listing 3.2 PWA News sw-reg.js File

// does the browser support service workers?
if ('serviceWorker' in navigator) {
  // then register our service worker
  navigator.serviceWorker.register('/sw.js')
    .then(reg => {
      // display a success message
      console.log(`Service Worker Registration (Scope: ${reg.scope})`);
    })
    .catch(error => {
      // display an error message
      let msg = `Service Worker Error (${error})`;
      console.error(msg);
      // display a warning dialog (using Sweet Alert 2)
      Swal.fire('', msg, 'error');
    });
} else {
  // happens when the app isn't served over a TLS connection (HTTPS)
  // or if the browser doesn't support service workers
  console.warn('Service Worker not available');
}

The code here isn’t very complicated; it all centers around the call to navigator.serviceWorker.register. The code first checks to see if the serviceWorker object exists in the browser’s navigator object. If it does, then this browser supports service workers. After the code verifies it can register the service worker, it does so through the call to navigator.serviceWorker.register.

The register method returns a promise, so the code includes then and catch methods to act depending on whether the installation succeeded or failed. If it succeeds, it tosses a simple message out to the console. If the call to register fails (caught with the catch method), we warn the user with an alert dialog.

Two potential error conditions exist here: if the browser doesn’t support service workers and if service worker registration fails. When the browser doesn’t support service workers, I log a simple warning to the console (using console.warn). I don’t do anything special to warn the user because this is progressive enhancement, right? If the browser doesn’t support service workers, the user just continues to use the app as is, with no special capabilities provided through service workers.

On the other hand, if registration fails, then the code is broken (because we already know the browser supports service workers), and I want to let you know more obnoxiously with an alert dialog. I did this because you’re learning how this works, and I wanted the error condition to be easily recognized. I probably wouldn’t do this for production apps because if the service worker doesn’t register, the app simply falls back to the normal mode of operation.

Service workers don’t start working until the next page loads anyway, so to keep things clean, you can defer registering the service worker until the app finishes loading, as shown in Listing 3.3.

Listing 3.3 PWA News sw-reg.js File (Alternate Version)

// does the browser support service workers?
if ('serviceWorker' in navigator) {
  // Defer service worker installation until the page completes loading
  window.addEventListener('load', () => {
    // then register our service worker
    navigator.serviceWorker.register('/sw.js')
      .then(reg => {
        // display a success message
        console.log(`Service Worker Registration (Scope: ${reg.scope})`);
      })
      .catch(error) => {
        // display an error message
        let msg = `Service Worker Error (${error})`;
        console.error(msg);
        // display a warning dialog (using Sweet Alert 2)
        Swal.fire('', msg, 'error');
      });
  })
} else {
    // happens when the app isn't served over a TLS connection (HTTPS)
    // or if the browser doesn't support service workers
    console.warn('Service Worker not available');
}

In this example, the code adds an event listener for the load event and starts service worker registration after that event fires. All this does is defer the additional work until the app is done with all its other startup stuff and shouldn’t even be noticeable to the user.

Next, let’s create a service worker. Create a new file called public/sw.js and populate it with the code shown in Listing 3.4. Notice that we created the service worker registration file in the project’s public/js/ folder, but this one goes into the web app’s root folder (public/); I’ll explain why in “Service Worker Scope” later in this chapter—I’m just mentioning it now to save you a potential problem later if you put it in the wrong place.

Listing 3.4 First Service Worker Example: sw-34.js

self.addEventListener('fetch', event => {
  // fires whenever the app requests a resource (file or data)
  console.log(`SW: Fetching ${event.request.url}`);
});

This code is simple as well. All it does is create an event listener for the browser’s fetch event, then logs the requested resource to the console. The fetch event fires whenever the browser, or an app running in the browser, requests an external resource (such as a file or data). This is different from the JavaScript fetch method, which enables an app’s JavaScript code to request data or resources from the network. The browser requesting resources (such as a JavaScript or image file referenced in an HTML script or img tag) and a web app’s JavaScript code requesting a resource using the fetch method will both cause the fetch event to fire.

This is the core functionality of a service worker, intercepting fetch events and doing something with the request—such as getting the requested resource from the network, pulling the requested file from cache, or even sending something completely different to the app requesting the resource. It’s all up to you: your service worker delivers as much or as little enhancement as needed for your app.

With this file in place, refresh the app in the browser and watch what happens. Nothing, right? There’s not much to see here since, everything happens under the covers. In this example, the service worker does nothing except log the event; as you can see in the browser, the app loaded as expected, so the app’s still working the same as it did before.

Open the browser’s developer tools and look for a tab labeled Application (or something similar) and a side tab labeled Service Workers. If you did everything right, you should see your service worker properly registered in the browser, as shown in Figure 3.5 (in Google Chrome).

FIGURE 3.5

Figure 3.5 Chrome Developer Tools Application Tab

If the browser can’t register the service worker, it displays error messages in this panel to let you know.

In the latest Chrome browser and the Chromium-based Edge browser, you can also open a special page that displays information about all service workers registered in the browser. Open the browser and enter the following value in the address bar:

chrome://serviceworker-internals/

The browser opens the page shown in Figure 3.6, listing all registered service workers.

FIGURE 3.6

Figure 3.6 Chrome Service Worker Internals Page

The one thing missing from the service worker as it stands today is for it to actually do something with the fetch request. Listing 3.5 adds an additional line of code to our existing service worker:

event.respondWith(fetch(event.request));

This code instructs the browser to go ahead and get the requested file from the network. Without this statement in the event listener, the browser was doing this anyway. Since the event listener didn’t act on the request and return a promise telling the browser it was dealing with it, then the browser goes ahead and gets the file anyway. That’s why the app works without this line. Adding the line just completes the event listener.

Listing 3.5 Second Service Worker Example: sw-35.js

self.addEventListener('fetch', event => {
  // fires whenever the app requests a resource (file or data)
  console.log(`SW: Fetching ${event.request.url}`);
  // next, go get the requested resource from the network,
  // nothing fancy going on here.
  event.respondWith(fetch(event.request));
});

The browser passes the fetch event listener an event object service workers query to determine which resource was requested. Service workers use this mechanism to determine whether to get the resource from cache or request it from the network. I cover this in more detail later (in this chapter and the next), but for now this extra line of code simply enforces what we’ve already seen the browser do—get the requested resource from the network.

The browser fires two other events of interest to the service worker developer: install and activate. Listing 3.6 shows a service worker with event listeners for both included.

Listing 3.6 Third Service Worker Example: sw-36.js

self.addEventListener('install', event => {
  // fires when the browser installs the app
  // here we're just logging the event and the contents
  // of the object passed to the event. the purpose of this event
  // is to give the service worker a place to setup the local
  // environment after the installation completes.
  console.log(`SW: Event fired: ${event.type}`);
  console.dir(event);
});

self.addEventListener('activate', event => {
  // fires after the service worker completes its installation.
  // It's a place for the service worker to clean up from
  // previous service worker versions.
  console.log(`SW: Event fired: ${event.type}`);
  console.dir(event);
});

self.addEventListener('fetch', event => {
  // fires whenever the app requests a resource (file or data)
  console.log(`SW: Fetching ${event.request.url}`);
  // next, go get the requested resource from the network,
  // nothing fancy going on here.
  event.respondWith(fetch(event.request));
});

The browser fires the install event when it completes installation of the service worker. The event provides the app with an opportunity to do the setup work required by the service worker. At this point, the service worker is installed but not yet operational (it doesn’t do anything yet).

The browser fires the activate event when the current service worker becomes the active service worker for the app. A service worker works at the browser level, not the app level, so when the browser installs it, it doesn’t become active until the app reloads in all browser tabs running the app. Once it activates, it stays active for any browser tabs running the app until the browser closes all tabs for the app or the browser restarts.

The activate event provides service workers with an opportunity to perform tasks when the service worker becomes the active service worker. Usually, this means cleaning up any cached data from a previous version of the app (or service worker). You’ll learn a lot more about this in Chapter 4, “Resource Caching”; for now, let’s add this code to our existing service worker and see what happens.

Once you’ve updated the code, reload the page in the browser, then open the developer tools console panel and look for the output shown in Figure 3.7. Chances are, you won’t see it—that’s because the previous version of the service worker is still active. You should see the install event fire but not the activate event.

FIGURE 3.7

Figure 3.7 Chrome Browser Tools Console Pane with Installation Output

You have several options for activating this new service worker. I explain two here and cover programmatic options in “The Service Worker Lifecycle” later in the chapter. One option is to close and reopen the browser, then reload the app; this automatically enables the registered service worker.

Another option is to configure the browser developer tools to automatically activate the new service worker once it registers the service worker; this approach is useful only when debugging or testing a PWA. At the top of the service workers pane shown in Figure 3.5 is a checkbox labeled Update on reload; when you enable (check) this checkbox, the browser automatically updates and activates new service workers every time you reload the page with a new service worker.

Force the browser to activate the new service worker, then look at the console page. You should now see the output shown in Figure 3.8 with each network request logged to the console.

FIGURE 3.8

Figure 3.8 Chrome Browser Tools Console Pane with Service Worker Output

At this point, the app has a functioning service worker listening for all relevant events and fetching all requested resources from the network. In the next sections, we talk about service worker scope (as promised) and the service worker lifecycle; then I’ll show you more you can do with service workers.

  • + Share This
  • 🔖 Save To Your Account