Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Service Worker Development Cookbook
Service Worker Development Cookbook
Service Worker Development Cookbook
Ebook758 pages2 hours

Service Worker Development Cookbook

Rating: 0 out of 5 stars

()

Read preview

About this ebook

About This Book
  • Get straight into the action with step-by-step recipes that show you how to put Service Workers to work
  • Find out what Service Workers can do for your app, then do it!
  • Get the first in-depth look at this important new feature for web developers
Who This Book Is For

Web developers, mobile application developers, and software engineers with any level of knowledge can use this book. You should be familiar with JavaScript and HTML.

LanguageEnglish
Release dateSep 1, 2016
ISBN9781786469526
Service Worker Development Cookbook

Related to Service Worker Development Cookbook

Related ebooks

Internet & Web For You

View More

Related articles

Reviews for Service Worker Development Cookbook

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Service Worker Development Cookbook - Sean Amarasinghe

    Table of Contents

    Service Worker Development Cookbook

    Credits

    About the Author

    About the Reviewer

    www.PacktPub.com

    eBooks, discount offers, and more

    Why subscribe?

    Preface

    What this book covers

    What you need for this book

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. Learning Service Worker Basics

    Introduction

    Service workers

    Promises

    Promise.resolve(value)

    Promise.reject(reason)

    Setting up service workers

    Getting ready

    How to do it...

    Chrome

    Firefox

    Setting up SSL for Windows

    Getting ready

    How to do it...

    Setting up SSL for Mac

    Getting ready

    How to do it...

    Setting up GitHub pages for SSL

    Getting ready

    How to do it...

    Registering a service worker

    Getting ready

    How to do it...

    How it works...

    There's more...

    Known issues

    The ERR_FILE_EXISTS error message

    Stale console messages

    Registering a service worker in detail

    Getting ready

    How to do it...

    How it works...

    There's more...

    Install

    Activate

    Fetch

    Terminate

    See also

    Debugging

    Getting ready

    How to do it...

    There's more...

    Providing a stale version on error

    Getting ready

    How to do it...

    How it works...

    There's more...

    Creating mock responses

    Getting ready

    How to do it...

    How it works...

    Handling request timeouts

    Getting ready

    How to do it...

    How it works...

    There's more...

    2. Working with Resource Files

    Introduction

    Displaying a custom offline page

    Getting ready

    How to do it...

    How it works...

    There's more...

    See also

    Loading images offline

    Getting ready

    How to do it...

    How it works...

    There's more...

    Handling responsive images

    The srcset attribute

    Device-pixel ratio

    The sizes attribute

    The picture element

    See also

    Loading CSS offline

    Getting ready

    How to do it...

    How it works...

    Loading fonts offline

    Getting ready

    How to do it...

    How it works...

    There's more...

    See also

    Implementing multiple fetch handlers

    Getting ready

    How to do it...

    How it works...

    There's more...

    See also

    Fetching remote resources

    Getting ready

    How to do it...

    How it works...

    There's more...

    No credentials by default

    Non-CORS fail by default

    See also

    3. Accessing Offline Content

    Introduction

    Caching critical resources for offline use

    Getting ready

    How to do it...

    How it works...

    See also

    Showing cached content first

    Getting ready

    How to do it...

    How it works...

    Implementing a cache and network race

    Getting ready

    How to do it...

    How it works...

    Using window.caches

    Getting ready

    How to do it...

    How it works...

    Implementing stale-while-revalidate

    Getting ready

    How to do it...

    How it works...

    4. Accessing Offline Content with Advanced Techniques

    Introduction

    Templating

    Getting ready

    How to do it...

    How it works...

    See also

    Implementing read-through caching

    Getting ready

    How to do it...

    How it works...

    Allowing offline Google Analytics

    Getting ready

    How to do it...

    How it works...

    See also

    Allowing offline user interaction

    Getting ready

    How to do it...

    How it works...

    Implementing selective caching

    Getting ready

    How to do it...

    How it works...

    See also

    5. Reaching Beyond the Offline Cache

    Introduction

    Getting network responses offline

    Getting ready

    How to do it...

    How it works...

    Caching content from ZIP

    Getting ready

    How to do it...

    How it works...

    Selecting the best content provider (load balancer)

    Getting ready

    How to do it...

    How it works...

    Redirecting a request

    Getting ready

    How to do it...

    How it works...

    Setting request headers

    Getting ready

    How to do it...

    How it works...

    Making a service worker act like a remote server

    Getting ready

    How to do it...

    How it works...

    Making a service worker act as a dependency injector

    Getting ready

    How to do it...

    How it works...

    Forcing immediate control

    Getting ready

    How to do it...

    How it works...

    Implementing fallback responses

    Getting ready

    How to do it...

    How it works...

    Deferring offline requests

    Getting ready

    How to do it...

    How it works...

    See also

    6. Working with Advanced Libraries

    Introduction

    Working with global APIs

    Getting ready

    How to do it...

    How it works...

    Cache

    caches

    fetch

    getAll

    Implementing a circuit breaker

    Getting ready

    How to do it...

    How it works...

    Implementing a dead letter queue

    Getting ready

    How to do it...

    How it works...

    Logging API analytics

    Getting ready

    How to do it...

    How it works...

    Working with Google Analytics

    Getting ready

    How to do it...

    How it works...

    See also

    7. Fetching Resources

    Introduction

    Fetching remote resources

    Getting ready

    How to do it...

    How it works...

    Fetching with FetchEvent

    Getting ready

    How to do it...

    How it works...

    Cache.addAll()

    ExtendableEvent.waitUntil()

    FetchEvent.respondWith()

    Fetching a JSON file during service worker installation

    Getting ready

    How to do it...

    How it works...

    Proxying

    Getting ready

    How to do it...

    How it works...

    Prefetching

    Getting ready

    How to do it...

    How it works...

    8. Experimenting with Web Push

    Introduction

    Implementing a simple push notification

    Getting ready

    How to do it...

    How it works...

    Showing rich notifications

    Getting ready

    How to do it...

    How it works...

    Using the notification tag

    Getting ready

    How to do it...

    How it works...

    Implementing push clients

    Getting ready

    How to do it...

    How it works...

    Subscribing to push notifications

    Getting ready

    How to do it...

    How it works...

    Managing push notification quotas

    Getting ready

    How to do it...

    How it works...

    9. Looking at General Usage

    Introduction

    Taking immediate control of the page

    Getting ready

    How to do it...

    How it works...

    Working with slow responses

    Getting ready

    How to do it...

    How it works...

    Relaying messages

    Getting ready

    How to do it...

    How it works...

    Using a service worker as a proxy middleware

    Getting ready

    How to do it...

    How it works...

    Using a service worker with a live flowchart

    Getting ready

    How to do it...

    How it works...

    10. Improving Performance

    Introduction

    Performing network requests from a cache

    Getting ready

    How to do it...

    How it works...

    See also

    Performing network requests from a network

    Getting ready

    How to do it...

    How it works...

    See also

    Testing waitUntil

    Getting ready

    How to do it...

    How it works...

    Implementing background sync

    Getting ready

    How to do it...

    How it works...

    Sending forward requests

    Getting ready

    How to do it...

    How it works...

    Avoiding model fetching and render times

    Getting ready

    How to do it...

    How it works...

    Index

    Service Worker Development Cookbook


    Service Worker Development Cookbook

    Copyright © 2016 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: August 2016

    Production reference: 1260816

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78646-529-0

    www.packtpub.com

    Credits

    Author

    Sean Amarasinghe

    Reviewer

    Daijiro Wachi

    Commissioning Editor

    David Barnes

    Acquisition Editor

    Nitin Dasan

    Content Development Editor

    Mehvash Fatima

    Technical Editor

    Siddhi Rane

    Copy Editors

    Safis Editing

    Tom Jacob

    Project Coordinator

    Kinjal Bari

    Proofreader

    Safis Editing

    Indexer

    Hemangini Bari

    Graphics

    Kirk D'Penha

    Production Coordinator

    Shantanu N. Zagade

    Cover Work

    Shantanu N. Zagade

    About the Author

    Sean Amarasinghe is a software developer from Melbourne, Australia. He is a developer, designer, photographer, and also a blogger. He blogs about development, design, technology, and photography. He is passionate about offline apps and what they bring to the user. He has firsthand experience of how well offline apps work. He has written a couple of blog posts about offline cache manifests, as well as service workers.

    About the Reviewer

    Daijiro Wachi is a JavaScript developer from Tokyo, Japan. He is passionate about open web and some of open source projects/communities related to JavaScript on a daily basis. He has gained the highest award in Service Worker Hackathon 2015 held by Google Japan.

    www.PacktPub.com

    eBooks, discount offers, and more

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    https://www2.packtpub.com/books/subscription/packtlib

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Preface

    The service worker feature of the browser will enable you to build highly available and performant native web applications that seamlessly integrate with third-party APIs. Whether you want to create an offline web app or a proxy, this book will show you how to do it.

    What this book covers

    Chapter 1, Learning Service Worker Basics, covers setting up the service worker in your environment, and how to get up and running using service worker development. This chapter includes registering a service worker and debugging.

    Chapter 2, Working with Resource Files, provides several recipes on how to handle resource files with the service worker, including loading CSS and fonts.

    Chapter 3, Accessing Offline Content, takes a look at how to cache resources and serve content offline.

    Chapter 4, Accessing Offline Content with Advanced Techniques, explores advanced techniques, including templating and Google Analytics, when working with offline content.

    Chapter 5, Reaching Beyond the Offline Cache, provides recipes beyond the offline cache and explores topics ranging from getting network responses offline to how to use the service worker as a load balancer.

    Chapter 6, Working with Advanced Libraries, talks about Google Analytics, circuit breakers, and dead letter queues.

    Chapter 7, Fetching Resources, covers various techniques on fetching resources from different sources.

    Chapter 8, Experimenting with Web Push, talks about different ways of implementing push notifications.

    Chapter 9, Looking at General Usage, provides various recipes on general usages of the service worker from slow responses to a live flowchart.

    Chapter 10, Improving Performance, talks about how to optimize your service worker application to perform efficiently and in a performant manner.

    What you need for this book

    This book was written using a Mac with Google Chrome as the browser, running Node.js. However, Node.js can be run on a Windows or Linux machine as well, along with Google Chrome.

    All the software used in this book is free and open source. You will definitely need to be running Node.js and Google Chrome for most of the recipes.

    Conventions

    In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

    Code words in text, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: The skipWaiting() method is used inside the active event handler, which in turn uses Clients.claim().

    A block of code is set as follows:

    self.oninstall = function(event) {

      event.waitUntil(

        fetch(zipURL)

          .then(function(res) {

            return res.arrayBuffer();

          })

          .then(getZipFileReader)

          .then(cacheFileContents)

          .then(self.skipWaiting.bind(self))

      );

    };

    Any command-line input or output is written as follows:

    $ git add –all $ git commit -m initial commit $ git push -u origin master

    New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes, for example, appear in the text like this: Finally, in the sidebar on the left-hand side, select Credentials.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

    To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    You can download the code files by following these steps:

    Log in or register to our website using your e-mail address and password.

    Hover the mouse pointer on the SUPPORT tab at the top.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box.

    Select the book for which you're looking to download the code files.

    Choose from the drop-down menu where you purchased this book from.

    Click on Code Download.

    You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

    Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

    WinRAR / 7-Zip for Windows

    Zipeg / iZip / UnRarX for Mac

    7-Zip / PeaZip for Linux

    The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Service-Worker-Development-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.

    We appreciate your help in protecting our authors and our ability to bring you valuable content.

    Questions

    If you have a problem with any aspect of this book, you can contact us at <questions@packtpub.com>, and we will do our best to address the problem.

    Chapter 1. Learning Service Worker Basics

    In this chapter, we will cover the following topics:

    Setting up service workers

    Setting up SSL for Windows

    Setting up SSL for Mac

    Setting up GitHub pages for SSL

    Registering a service worker

    Registering a service worker in detail

    Debugging

    Providing stale version on error

    Creating mock responses

    Handling request timeouts

    Introduction

    If you travel a bit, chances are you have probably found yourself stuck with zero network connectivity way too often. This is frustrating, especially if you just wanted to continue reading some news articles, blog posts, or you wanted to get some work done.

    Unfortunately, with your browser, attempting to make requests for something from the network while being offline doesn't quite work out so well.

    Even though on planes, the subway, in hotels, and at conferences, Wi-Fi may provide you with opportunities to restore your connection, in general you will have to wait for the network to return online in order to request the pages you want to view.

    Previous attempts to solve this issue include AppCache. It seems to work, to some extent, but the issue with AppCache is that it makes a lot of assumptions about user interactions. When those assumptions are not met, the application will fail to function as expected. It is also designed to work well with single page apps, not the traditional multi-page websites.

    Also, one of the most challenging problems with providing a seamless user experience with web apps is making them functional while offline. This is an important issue to resolve, given that most users today access web apps on the move. Enter service workers, a script running in the background of our browser.

    Being able to use a web app, regardless of the connectivity, means users can operate uninterrupted when they are on board a plane, the subway, or in places where connectivity is limited or not available. This technology will help boost client productivity and will increase the availability of the application.

    With service workers, we are able to pre-cache some assets of a website. What we are referencing as assets are JavaScript files, CSS files, images, and some fonts. This will help us to speed up the loading time, instead of having to fetch information from the web servers every time we visit the same website. And of course, most importantly, those assets will be available for us when we are offline.

    Service workers

    A service worker is a script that stands between your browser and the network, giving you, among

    Enjoying the preview?
    Page 1 of 1