service workers your applications never felt so good

64
Service Workers Your Web App Never Felt So Good LOVE2DEV.CO M

Upload: chris-love

Post on 07-Jan-2017

397 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Service workers   your applications never felt so good

Service WorkersYour Web App Never Felt So Good

LOVE2DEV.COM

Page 2: Service workers   your applications never felt so good

My BioMicrosoft MVPASP Insider Edge User AgentWeb Developer 25 yearsAuthor & Speaker

@ChrisLoveLove2Dev.com

Page 3: Service workers   your applications never felt so good

Slide Decks & Source Code

Source Codehttp://

GitHub.com/docluv

Slide Deck http://slideshare.net/docluv/presentations

LOVE2DEV.COM

Page 4: Service workers   your applications never felt so good

LOVE2DEV.COM

What is a Modern Web Application?Defining the Front-End

Page 5: Service workers   your applications never felt so good

“Progressive Web Applications: A New Level of Thinking About the Quality of Your User Experience”

https://www.youtube.com/watch?v=EErueQdEXMA Chris Wilson, Google

Page 6: Service workers   your applications never felt so good

“Native Apps are a bridging technology (like Flash)”

http://bit.ly/2e5Cgry

Bruce Lawson, Opera

Page 7: Service workers   your applications never felt so good

Peak App?75% Use 3 or fewer apps per month.

comscore.com/USMobileAppReport2016

Page 8: Service workers   your applications never felt so good

LOVE2DEV.COM

Page 9: Service workers   your applications never felt so good

LOVE2DEV.COM

But the Web Can’t…• Add to the Homescreen•Work Offline• Persist Data Between Sessions• Do Push Notifications• Access the Camera• Store Files• Connect to my Boat – Seriously?

Page 10: Service workers   your applications never felt so good

LOVE2DEV.COM

Oh But the Web Can & Does• Add to the Homescreen•Work Offline• Persist Data Between Sessions• Do Push Notifications• Access the Camera• Store Files• Connect to my Boat – Seriously, IoT & the Cloud

Page 11: Service workers   your applications never felt so good

LOVE2DEV.COM

Let’s See What Service Workers Offer•Work Offline

• Persist Data Between Sessions

•Do Push Notifications

•More…

Page 12: Service workers   your applications never felt so good

LOVE2DEV.COM

PWAProgressive Web Applications

Page 13: Service workers   your applications never felt so good

PWA Features•“install” to the home screen•have their own icon (defined by the web developer)•can launch full-screen, portrait or landscape•but “live” on the Web

LOVE2DEV.COM

Page 14: Service workers   your applications never felt so good

PWA Features• live on the server so no update distribution lag•require no app store or gatekeeper•can work offline•are a normal website on browsers such as Opera Mini, Safari, Windows phones•searchable, indexable, linkable

LOVE2DEV.COM

Page 15: Service workers   your applications never felt so good

PWA Features•“Feels” like a normal app•Push Notifications (optional)•Background Sync (optional)

LOVE2DEV.COM

Page 16: Service workers   your applications never felt so good

“These apps aren’t packaged & deployed through stores, they’re just websites that took the right vitamins.

They progressively become apps…”

Alex RussellGoogle

Page 17: Service workers   your applications never felt so good

PWA Updates•AppCache -> Service Worker• localStorage -> IndexDB•Touch Icons -> Manifest•Save to Homescreen -> Install Banner

LOVE2DEV.COM

Page 18: Service workers   your applications never felt so good

LOVE2DEV.COM

PWA Requirements•HTTPS•Manifest• Service Worker

{ name: “your application”, …}

Page 19: Service workers   your applications never felt so good

LOVE2DEV.COM

PWA Requirements•HTTPS•Manifest•Service Worker

{ name: “your application”, …}

Page 20: Service workers   your applications never felt so good

Application Loading Process

The 1st Time a User Visits They ‘Install’ the Application

Page 21: Service workers   your applications never felt so good

LOVE2DEV.COM

HTTPS•Because PWAs Require a Service Worker They Must Be Secure•HTTPS Protects Against Man in the Middle Atacks

Page 22: Service workers   your applications never felt so good

LOVE2DEV.COM

HTTPS•Certificates Are Cheap Today•LetsEncrypt.org•AWS Certificate Manager

Page 23: Service workers   your applications never felt so good

LOVE2DEV.COM

Service Workers•Allow Offline Capabilities•Native Resource Caching•Allow Push Notifications•Data Synch*

* Near Future

Page 24: Service workers   your applications never felt so good

LOVE2DEV.COM

Service WorkersMore Than an AppCache Replacement

Page 25: Service workers   your applications never felt so good

LOVE2DEV.COM

Service Workers• allows developers to cache assets when connected, and intercept failed calls to network when offline, so user experience can be maintained

Page 26: Service workers   your applications never felt so good

LOVE2DEV.COM

Service Workers• Faster loading of assets, even when online• Fastest HTTP Request is the One Never Made

Page 27: Service workers   your applications never felt so good

LOVE2DEV.COM

Service Workers•Push Notifications

Even When Browser Is Closed

Page 28: Service workers   your applications never felt so good

LOVE2DEV.COM

if ('serviceWorker' in navigator) {     navigator.serviceWorker.register('/sw.js')

.then(function(registration) {       // Registration was successful    })

.catch(function(err) {       // registration failed :(    }); }

Page 29: Service workers   your applications never felt so good

LOVE2DEV.COM

self.addEventListener('install', function (e) {

//do something

});

Page 30: Service workers   your applications never felt so good

LOVE2DEV.COM

self.addEventListener('activate', function (event) { console.log('Service Worker activating.');});

Page 31: Service workers   your applications never felt so good

LOVE2DEV.COM

Web Server

Web Page

Page 32: Service workers   your applications never felt so good

LOVE2DEV.COM

Web ServerWeb

Page

Service Worker

Page 33: Service workers   your applications never felt so good

LOVE2DEV.COM

Web ServerWeb

Page

Service Worker

Page 34: Service workers   your applications never felt so good

LOVE2DEV.COM

Web ServerWeb

Page

Service Worker

Cache

Page 35: Service workers   your applications never felt so good

LOVE2DEV.COM

Service Worker Cache• Persist Files with Response Headers• Limited by Device Resources• Available Online & Offline

Page 36: Service workers   your applications never felt so good

LOVE2DEV.COM

self.addEventListener('install', function (e) {

e.waitUntil( caches.open(cacheName).then(function (cache) {

return cache.addAll(filesToCache).catch(function (error) { console.log(error);

}); }) );});

Page 37: Service workers   your applications never felt so good

LOVE2DEV.COM

self.addEventListener('fetch', function (event) {

//intercept fetch request (any request from the UI thread for a file or API) and return from cache or get from server & cache it event.respondWith(

caches.match(event.request).then(function (resp) {

return resp || fetchAsset(event);

})

);

});

Page 38: Service workers   your applications never felt so good

LOVE2DEV.COM

Service Worker Cache• Persist Files with Response Headers• Limited by Device Resources• Available Online & Offline

Page 39: Service workers   your applications never felt so good

LOVE2DEV.COM

Web ServerWeb

Page

Service Worker

CacheIndexDB

Page 40: Service workers   your applications never felt so good

LOVE2DEV.COM

5 Bars!

Page 41: Service workers   your applications never felt so good

LOVE2DEV.COM

No Bars

Page 42: Service workers   your applications never felt so good

LOVE2DEV.COM

1 Bar

Page 43: Service workers   your applications never felt so good

LOVE2DEV.COM

Lie-Fi :/

Page 44: Service workers   your applications never felt so good

LOVE2DEV.COM

Handling Offline

Page 45: Service workers   your applications never felt so good

LOVE2DEV.COM

Web Page

Service Worker

Page 46: Service workers   your applications never felt so good

LOVE2DEV.COM

Web Page

Service Worker

Cache

Page 47: Service workers   your applications never felt so good

LOVE2DEV.COM

Offline API if (!navigator.onLine) {

console.log("you are offline");}

window.addEventListener('online', function () {console.log("you have gone offline");

});

window.addEventListener('offline', function () {console.log("you are back online");

});

Page 48: Service workers   your applications never felt so good

LOVE2DEV.COM

Debugging Service Workers•Use Developer Tools• Sources• Application

• Manifest• Service Workers

Page 49: Service workers   your applications never felt so good

LOVE2DEV.COM

Web Server

Web Page

Service Worker

Cache

2

1

Page 50: Service workers   your applications never felt so good

LOVE2DEV.COM

Web Server

Web Page

Service Worker

Cache

2

Page 51: Service workers   your applications never felt so good

LOVE2DEV.COM

self.addEventListener('install', function (e) {

e.waitUntil(…

}) );

self.skipWaiting();

});

Page 52: Service workers   your applications never felt so good

LOVE2DEV.COM

Service Worker Tools• sw_precache• A node module to generate service worker code that will

precache specific resources so they work offline.• https://github.com/googlechrome/sw-precache

• sw_toolbox• A collection of service worker tools for offlining runtime

requests • https://github.com/GoogleChrome/sw-toolbox

Page 53: Service workers   your applications never felt so good

LOVE2DEV.COM

Service Worker Resources• Is Service Worker Ready?• https://jakearchibald.github.io/isserviceworkerready/

• Service Worker Cookbook• https://serviceworke.rs/

Page 54: Service workers   your applications never felt so good

LOVE2DEV.COM

Immersion

Page 55: Service workers   your applications never felt so good

LOVE2DEV.COM

Add Application to Home Screen•Has a web app manifest file with:• a short_name (used on the home screen)• a name (used in the banner)

• a 144x144 png icon• a start_url that loads•Has a service worker registered on your site.• Is served over HTTPS (.• Is visited at least twice, with at least five minutes between visits.

Page 56: Service workers   your applications never felt so good

LOVE2DEV.COM

Page 57: Service workers   your applications never felt so good

LOVE2DEV.COM

Page 58: Service workers   your applications never felt so good

LOVE2DEV.COM

Push Notifications• Require Service Worker so they operate in the background•Work even when the browser is closed

Page 59: Service workers   your applications never felt so good

LOVE2DEV.COM

• 72% increase in time spent for users visiting via a push notification• 26% increase in average spend per visit by members arriving via a push notification•+50% repeat visits within 3 month

Page 60: Service workers   your applications never felt so good

LOVE2DEV.COM

Two Technologies•push is invoked when a server supplies information to a service worker; • a notification is the action of a showing information to a user

Page 61: Service workers   your applications never felt so good

LOVE2DEV.COM

serviceWorkerRegistration.showNotification(title, options);

Page 62: Service workers   your applications never felt so good

LOVE2DEV.COM

{  "body": "Did you make a $1,000,000 purchase at Dr. Evil...",  "icon": "images/ccard.png",  "vibrate": [200, 100, 200, 100, 200, 100, 400],  "tag": "request",  "actions": [    { "action": "yes", "title": "Yes", "icon": "images/yes.png" },    { "action": "no", "title": "No", "icon": "images/no.png" }  ]}

Page 63: Service workers   your applications never felt so good

LOVE2DEV.COM

Request User Permissionfunction initialiseState() {  if (Notification.permission !== 'granted') {    console.log('The user has not granted the notification permission.');    return;  } else if (Notification.permission === “blocked”) {   /* the user has previously denied push. Can't reprompt. */  } else {    /* show a prompt to the user */  }

Page 64: Service workers   your applications never felt so good

LOVE2DEV.COM

Request User Permission  // Use serviceWorker.ready so this is only invoked  // when the service worker is available.  navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {    serviceWorkerRegistration.pushManager.getSubscription()      .then(function(subscription) {        if (!subscription) {          // Set appropriate app states.          return;        }      })      .catch(function(err) {        console.log('Error during getSubscription()', err);      });  });}