Service Worker Presentation

28
Service Worker

Transcript of Service Worker Presentation

Page 1: Service Worker Presentation

Service Worker

Page 2: Service Worker Presentation

Overview

● What is a Service Worker?● What existed before the Service Worker?● Lifecycle of a Service Worker● Use cases● A fair assessment (a.k.a. the bad)

Page 3: Service Worker Presentation

What is a service worker?

Page 4: Service Worker Presentation

A service worker is a script that is run by your browser in the background,

separate from a web page

Page 5: Service Worker Presentation

● It's a JavaScript Worker, so it can't access the DOM directly

● Service worker is a programmable network proxy, allowing you to control how network requests from your page are handled.

● It will be terminated when not in use, and restarted when it's next needed

● Service workers are asynchronous and make extensive use of promises

● Service workers require content to be served via https

Page 6: Service Worker Presentation

What existed before the Service Worker?

Page 7: Service Worker Presentation

AppCache

Page 8: Service Worker Presentation

CACHE MANIFESTassets/6/script/mainmin.jsassets/6/style/mainmin.cssassets/6/style/fonts/pro.ttfassets/6/style/imgs/sprites1.png

<html manifest="offline.appcache">

Page 9: Service Worker Presentation

Using the Service Worker

Page 10: Service Worker Presentation
Page 11: Service Worker Presentation

Service Worker Lifecycle

Page 12: Service Worker Presentation

1. The service worker URL is fetched and registered

if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/trained-to-thrill/sw.js') .then(function(reg) { console.log('success!', reg); }, function(err) { console.log('error!', err); });}

Page 13: Service Worker Presentation

2. If successful, the service worker is executed in a ServiceWorkerGlobalScope; this is basically a special kind of worker context, running off the main script execution thread, with no DOM access.

3. The service worker is now ready to process events.

Page 14: Service Worker Presentation

4. Installation of the worker is attempted when service worker-controlled pages are accessed subsequently. An Install event is always the first one sent to a service worker

5. Same procedure as installing a native app — making everything available for use offline.

Page 15: Service Worker Presentation

6. When the oninstall handler completes, the service worker is considered installed.

self.oninstall = function(event) { event.waitUntil( caches.open('trains-static-v14').then(function(cache) { return cache.addAll([ '/trained-to-thrill/', '/trained-to-thrill/static/css/all.css', '/trained-to-thrill/static/js/page.js', '/trained-to-thrill/static/imgs/logo.svg', '/trained-to-thrill/static/imgs/icon.png' ]); }) );};

Page 16: Service Worker Presentation

7. When the service worker is installed, it then receives an activate event. The primary use of onactivate is for cleanup of resources used in previous versions of a Service Worker script.

self.onactivate = function(event) { // remove caches beginning "trains-" that aren't in // expectedCaches event.waitUntil( caches.keys().then(function(cacheNames) { return Promise.all( cacheNames.map(function(cacheName) { if (!/^trains-/.test(cacheName)) { return; } if (expectedCaches.indexOf(cacheName) == -1) { return caches.delete(cacheName); }}));}));};

Page 17: Service Worker Presentation

8. The Service Worker will now control pages, but only those opened after the register() is successful. i.e. a document starts life with or without a Service Worker and maintains that for its lifetime. So documents will have to be reloaded to actually be controlled.

this.addEventListener('fetch', function(event) { var cachedResponse = caches.match(event.request).catch(function() { return event.default().then(function(response) { return caches.get('v1').then(function(cache) { cache.put(event.request, response.clone()); return response; }); }); }).catch(function() { return caches.match('/sw-test/gallery/myLittleVader.jpg'); }); event.respondWith(cachedResponse);});

Page 18: Service Worker Presentation

When to use?

Page 19: Service Worker Presentation

Cache assets specific to the version of the app

Page 20: Service Worker Presentation

Give the user a "Read later" or "Save for offline" button. When it's clicked, fetch what you need from the network & pop it in the cache.

Page 21: Service Worker Presentation

On network response: Frequently updating resources such as a user's inbox, tweets, images, or article contents.

Page 22: Service Worker Presentation

Push● The Push API is built on top of SerivceWorker. ● Allows the ServiceWorker to be awoken in response to

a message from the OS's messaging service. ● Happens even when the user doesn't have a tab open

to your site, only the ServiceWorker is woken up. ● You request permission to do this from a page & the

user will be prompted.

Page 23: Service Worker Presentation

Background Sync● Built on top of ServiceWorker. ● It allows you to request background data

synchronisation as a one-off, or on an (extremely heuristic) interval.

● This happens even when the user doesn't have a tab open to your site, only the ServiceWorker is woken up.

● You request permission to do this from a page & the user will be prompted.

Page 24: Service Worker Presentation

The bad news

Page 25: Service Worker Presentation
Page 26: Service Worker Presentation

● If installation fails, the browser is not good at telling you about it

● fetch() is only available in service workers● No credentials by default (cookies)● Non-CORS fail by default (opaque response)● Handling responsive images

Page 27: Service Worker Presentation

Demo

Page 28: Service Worker Presentation

Questions