Service Worker Presentation

Post on 15-Jul-2015

102 views 1 download

Transcript of Service Worker Presentation

Service Worker

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)

What is a service worker?

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

separate from a web page

● 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

What existed before the Service Worker?

AppCache

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

<html manifest="offline.appcache">

Using the Service Worker

Service Worker Lifecycle

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); });}

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.

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.

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' ]); }) );};

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); }}));}));};

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);});

When to use?

Cache assets specific to the version of the app

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.

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

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.

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.

The bad news

● 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

Demo

Questions