Book Image

Service Worker Development Cookbook

By : Sean Amarasinghe
Book Image

Service Worker Development Cookbook

By: Sean Amarasinghe

Overview of this book

It would be nice to have web apps that work offline and send push notifications. This is now possible with Service Workers, which can add native-like functionality to your web apps without requiring a download. This book will get your mobile and web apps functioning without Internet connectivity, improve performance and network interaction in order to increase the level of availability, and show you how to build performant applications that seamlessly integrate with third-party APIs. We’ll show you how to add Service Worker functionality to web apps and sites, access offline content through basic and advanced techniques, and build powerful interactive system notifications. We’ll also teach you about cache functionality and assets to provide immediate load even over narrow connections. We conclude by giving you various tips to improve app performance, including the background sync technique. By the end of this book, you’ll know build high performing and faster web and mobile applications with Service Workers.
Table of Contents (17 chapters)
Service Worker Development Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Registering a service worker


Registering your service worker is the first step to getting a service worker up and running. By registering a service worker, we tell our website to use the service worker. And this registering process happens outside of the service worker, in our case inside the index.html file. You can do that inside a JavaScript file and then reference it within the index.html file, but not in the service worker script file.

In this basic registration demo, we will test to see if our service worker gets registered successfully.

Getting ready

To get started, with service workers, you will need to have the service worker experiment feature turned on in your browser settings. If you have not done this yet, refer to the first recipe: Setting up service workers. Service workers only run across HTTPS. To find out how to set up a development environment to support this feature, refer to the following recipes: Setting up GitHub pages for SSL, Setting up SSL for Windows, and Setting up SSL for Mac.

How to do it...

Follow these instructions to set up your file structure:

  1. First, we need to create the index.html file as follows:

    <!DOCTYPE html>
      <html lang="en">
       <head></head>
           <body>
           <p>Registration status: <strong id="status"></strong></p>
           <script>
              if ('serviceWorker' in navigator) {
               navigator.serviceWorker.register(
                  'service-worker.js',
                  { scope: './' }
                ).then( function(serviceWorker) {
                  document.getElementById('status').innerHTML =
                        'successful';
                  }).catch(function(error) {
                      document.getElementById('status').innerHTML = error;
                  });
              } else {
                    document.getElementById('status').innerHTML = 
               'unavailable';
                }
    </script>
    </body>
    </html>
  2. Create an empty JavaScript file called service-worker.js in the same folder as the index.html file.

  3. With your two files in place, you can navigate to the GitHub page, https://username.github.io/service-workers/01/01/index.html, and you will see the success message in your browser.

How it works...

We started off by making sure that the service worker feature is available with the line if ('serviceWorker' in navigator). If that's not the case, then we set the message to unavailable. If your browser does not support service workers, you will get this message.

Now we register the service worker with the empty JavaScript file and the scope. To ensure the registration is only applicable to the current directory and those underneath it, we override the default scope of '/' with './' in the line { scope: './' } as the scope has to be of the same origin.

If you decide that your script files should sit elsewhere, you will need a special header, such as Service-Worker-allowed: true or a specific content-type, such as text/javascript.

If the registration was successful, we print the message successful to the status message.

Otherwise, we print the error message as the status. The reason for the error could be something going wrong during the registration, for example, the service-worker.js file may not available or it may contain a syntax error.

There's more...

We can unregister the service worker by calling the following unregister() function:

serviceWorker.unregister().then(function() {
    document.getElementById('status').innerHTML = 'unregistered';
})

Known issues

There are a couple of issues with the Chrome browser when working with service workers, which might confuse you.

The ERR_FILE_EXISTS error message

Reloading pages with service workers will always show an ERR_FILE_EXISTS error message, even if there's nothing wrong with your code.

This seems to occur when we are trying to access an already registered service worker.

Stale console messages

Logging messages from the service worker scripts such as the console.log may not clear from the console, which seems like the events are being fired too many times on subsequent page loads.