Service Worker Development Cookbook - Sean Amarasinghe - E-Book

Service Worker Development Cookbook E-Book

Sean Amarasinghe

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Build highly available and performant native web applications that seamlessly integrate with third-party APIs

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.

What You Will Learn

  • Display a custom offline page
  • Cache critical resources for offline use
  • Implement offline Google Analytics
  • Get network responses offline
  • Implement push notifications
  • Improve performance of your app

In Detail

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.

Style and approach

This book provides lots of task-oriented, practical, and inspiring ways to put Service Workers to work. Step-by-step instructions will guide you through every task.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 248

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



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 <[email protected]> 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 PacktCopy and paste, print, and bookmark contentOn 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.

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 <[email protected]>, 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 WindowsZipeg / iZip / UnRarX for Mac7-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 <[email protected]> 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 <[email protected]>, and we will do our best to address the problem.

Setting up service workers

In order to get service workers running, we need to serve our code via Hyper Text Transfer Protocol Secure (HTTPS). Service workers are designed to run only across HTTPS for security reasons. Source code repositories such as GitHub support HTTPS, where you can host your files.

Getting ready

If you are using a newer version of a browser, the chances are that service workers are already enabled on it. But, if that is not the case, we will have to change few things in the browser settings. In the following section, we are going to cover how to enable service worker features in Chrome and Firefox.

How to do it...

Follow the steps below to enable service worker in Chrome and Firefox.

Chrome

To experiment in Chrome, you need to download Chrome Canary:

Go to https://www.google.com/chrome/browser/canary.html and download the latest version.Open Chrome Canary and type chrome://flags.Turn on experimental-web-platform-features.Restart the browser.The following image shows experimental features on the Chrome browser, where you enable the Experimental Web Platform feature by clicking on the Enable link underneath:

Firefox

To experiment in Firefox, you need to download Firefox Nightly:

Go to https://nightly.mozilla.org/ and download the latest version.Open Firefox Nightly, and go to about:config.Set experimental-web-platform-features to true.Restart the browser.

Note

At the time of writing, Opera offers partial support for service workers, including basic support, as well as installing and uninstalling events. Internet Explorer and Safari do not support service workers.

Service workers are currently an experimental technology, meaning the syntax and the behavior are subject to change in future versions as the specification changes.

Setting up SSL for Windows

Service workers are designed to run only across HTTPS, so in order for us to test our code, we need our web pages to be delivered across HTTPS. In this recipe, we will cover getting your site setup with SSL support for Windows.

Getting ready

This recipe assumes you run Windows 7 or higher with Internet Information Service (IIS) enabled.

How to do it...

Follow these instructions to enable SSL:

First, open IIS; you can do this by running the following command inside the command line:
Inetmgr
Select the server node in the tree view and double-click the Server Certificates feature in the list view, as shown:Click on the Create Self-Signed Certificate... link in the Actions pane.Enter a meaningful name for the new certificate and click OK.

This will generate a self-signed certificate, which is marked for Server Authentication use, meaning it uses a server-side certificate for authenticating the identity of the server and also for HTTP SSL encryption.

In order to create an SSL binding, we have to select a site in the tree view and then, in the Actions pane, click Bindings.... This will bring up the bindings editor that manages bindings for your website, which include create, edit, and delete. Now, to add your new SSL binding to the site, click Add....

Port 80 is the default setting for a new binding for HTTP. We can select https in the Type drop-down list. Select the self-signed certificate we created in the previous section from the SSL Certificate drop-down list, and then click OK.Now we have a new SSL binding on our site and all that remains is to make sure that it works.Click Continue to this website to proceed.

Setting up SSL for Mac

As mentioned in the previous recipe, service workers are designed to run only across HTTPS. So, in order for us to test our code, we need our web pages to be delivered across HTTPS. In this recipe, we will cover getting your site set up with SSL support for Mac.

Getting ready

This recipe assumes that you are running OS X 10.11, El Capitan, or higher. We are going to use a command-line utility called Vim for editing files, which already comes with Mac. Make sure not to use the number pad with Vim. Please be aware that this process is lengthy.

How to do it...

Follow these instructions to enable SSL:

First, we need to make sure Apache is running (you may get a prompt for a password):
$ sudo apachectl start
The next step is to make some modifications to your httpd.conf. Because it's a system file, you will need to use sudo again:
$ sudo vim /etc/apache2/httpd.conf
In this file, you should uncomment both socache_shmcb_module and ssl_module, and also the include the httpd-ssl.conf file by removing the leading # symbol on those lines (you can use / to search on the Vim editor):
LoadModule socache_shmcb_module libexec/apache2/mod_socache_shmcb.so ... LoadModule ssl_module libexec/apache2/mod_ssl.so ... Include /private/etc/apache2/extra/httpd-ssl.conf
After saving the preceding file (press :wq), you should then open up your /etc/apache2/extra/httpd-vhosts.conf file:
$ sudo vim /etc/apache2/extra/httpd-vhosts.conf
Here, you can create a VirtualHost entry for each virtual host that you wish to provide SSL support for:
<VirtualHost *:80> DocumentRoot "/Library/WebServer/Documents" ServerName localhost SSLEngine on SSLCertificateFile "/private/etc/apache2/localhost.crt" SSLCertificateKeyFile "/private/etc/apache2/localhost.key" </VirtualHost>

Make sure you copy your development folder to the DocumentRoot directory as you did earlier: /Library/WebServer/Documents.

To get this all to work with Apache, we need to create a self-signed certificate that we have already referenced in the VirtualHost definition.

Generate a key:
$ cd /etc/apache2
Press Enter with no input after the following command:
$ sudo openssl genrsa -out localhost-key.pem 1024
Next, we have to generate a certificate signing request:
$ sudo openssl req -new -key localhost-key.pem -out localhost.csr
Using this certificate signing request (CSR), generate the certificate:
$ sudo openssl x509 -req -days 365 -in localhost.csr -signkey localhost-key.pem -out localhost.crt
Then we have to convert the key to a no-phrase key:
$ sudo openssl rsa -in localhost-key.pem -out localhost.key
Now change server.crt to localhost.crt as well as server.key to localhost.key:
$ sudo vim /etc/apache2/extra/httpd-ssl.conf
All you need to do now is double check your Apache configuration syntax:
$ sudo apachectl configtest
If all goes well, restart Apache:
$ sudo apachectl -k restart
Now, simply point your browser at https://localhost. If you are prompted for a self-signed certificate in Chrome you can hit the Advanced option on that page and proceed, while in Firefox, you need to expand the I understand the risks options and add an exception. This is owing to the fact that the self-signed certificates are not signed by any authority, and for this reason the browsers add warnings about them. Although, since you are the one who created the certificate, you understand it's safe to accept it.To fix this, you need to add the certificate as a trusted root authority.Open the Keychain Access utility in OS X. Select the System option on the left. Click the lock icon in the upper-left corner to enable changes.Click the plus button at the bottom and select the /etc/apache2/localhost.cer file you copied to the desktop. In the dialog that comes up, click Always Trust. After the localhost gets added to the system keychain, double-click it to open it again. Expand the Trust section and for the first option, pick Always Trust.At this point, everything has been configured. Quit Chrome and all other browsers (this is required), fire up the web server, and try to navigate to the local HTTPS site again.

Tip

Detailed steps to download the code bundle are mentioned in the Preface of this book. Please have a look.

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!

Setting up GitHub pages for SSL

Service workers are designed to run only across HTTPS. So, in order for us to test our code, we need our web pages to be delivered across HTTPS. GitHub pages are served across HTTPS and it's free to use. So let's get on with it.

Getting ready

Before registering for a GitHub account, please make sure you have a valid e-mail address.

How to do it...

Follow these instructions to set up GitHub pages:

Head over to GitHub (https://github.com) and register yourself to obtain an account, if you don't have one already.Once you have done that, log in and create a new repository with the following format:

username.github.io, where username is your username.

If the first part of the repository doesn't match your username exactly, it won't work.

Open your command-line window and clone your repository.
$ git clone https://github.com/username/username.github.io
Change the directory to username.github.io:
$ cd username.github.io
Create a directory called service-workers:
$ mkdir service-workers
Create an index.html file with some text:
$ echo "Service Workers" > index.html
Now let's commit and push our changes to the repository:
$ git add --all