Slide 1

Slide 1 text

Building an Offline Page for theguardian.com Oliver Joseph Ash – Front-Trends, May 2016
 @OliverJAsh

Slide 2

Slide 2 text

@OliverJAsh

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

web vs native

Slide 6

Slide 6 text

• Content is cached • Experience: • offline: stale content remains • server down: stale content remains • poor connection: stale while revalidate • good connection: stale while revalidate Native app

Slide 7

Slide 7 text

Experience: • offline: nothing • server down: nothing • poor connection: white screen of death • good connection: new content Website

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

We can do better!

Slide 10

Slide 10 text

/developer-blog

Slide 11

Slide 11 text

How it works

Slide 12

Slide 12 text

Prototype built in < 1 day

Slide 13

Slide 13 text

1

Slide 14

Slide 14 text

. Create and register the service worker 1

Slide 15

Slide 15 text

What is a service worker?

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

What is a service worker? • Script that runs in the background • Useful for features with no user interaction, e.g.: • listen to push events, useful for pushing notifications • intercept and handle network requests • future: • background sync • alarms (e.g. reminders) • geofencing • A progressive enhancement • Trusted origins only (HTTPS, localhost) • Chrome, Opera, and Firefox stable

Slide 18

Slide 18 text

www.theguardian.com https://

Slide 19

Slide 19 text

https://…/info …/science …/technology …/business

Slide 20

Slide 20 text

if (navigator.serviceWorker) { navigator.serviceWorker.register('/service-worker.js'); }

Slide 21

Slide 21 text

1 2

Slide 22

Slide 22 text

No content

Slide 23

Slide 23 text

No content

Slide 24

Slide 24 text

2

Slide 25

Slide 25 text

. Prime the cache 2

Slide 26

Slide 26 text

var version = 1; var staticCacheName = 'static' + version; var updateCache = function () { return caches.open(staticCacheName) .then(function (cache) { return cache.addAll([ '/offline-page', '/assets/css/main.css', '/assets/js/main.js' ]); }); }; self.addEventListener('install', function (event) { event.waitUntil(updateCache()); }); • install event: get ready! • Cache the assets needed later • Version the cache

Slide 27

Slide 27 text

1 2

Slide 28

Slide 28 text

3

Slide 29

Slide 29 text

. Handle requests with fetch 3

Slide 30

Slide 30 text

const staticCacheName = 'static'; const version = 1; const updateCache = () => ( caches.open(staticCacheName + version) .then(cache => cache.addAll([ '/offline-page.html', '/assets/css/main.css', '/assets/js/main.js' ]); ); ); self.addEventListener('install', function (event) { event.waitUntil(updateCache()); }); self.addEventListener('fetch', function (event) { event.respondWith(fetch(event.request)); }); • Default: just fetch • Override default • Intercept network requests to: • fetch from the network • read from the cache • construct your own response fetch events

Slide 31

Slide 31 text

No content

Slide 32

Slide 32 text

No content

Slide 33

Slide 33 text

• e.g., use templating to construct a HTML response from JSON Service worker: custom responses self.addEventListener('fetch', function (event) { var responseBody = '

Hello, World!

'; var responseOptions = { headers: { 'Content-Type': 'text/html' } }; var response = new Response( responseBody, responseOptions ); event.respondWith(response); });

Slide 34

Slide 34 text

Mutable (HTML) Immutable (assets: CSS, JS)

Slide 35

Slide 35 text

HTML

Slide 36

Slide 36 text

Network first, then cache

Slide 37

Slide 37 text

var doesRequestAcceptHtml = function (request) { return request.headers.get('Accept') .split(',') .some(function (type) { return type === ‘text/html’; }); }; self.addEventListener('fetch', function (event) { var request = event.request; if (doesRequestAcceptHtml(request)) { event.respondWith(fetch(request)); } });

Slide 38

Slide 38 text

self.addEventListener('fetch', function (event) { var request = event.request; if (doesRequestAcceptHtml(request)) { event.respondWith( fetch(request).catch(function () { return caches.match('/offline-page'); }) ); } });

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

Assets

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

self.addEventListener('fetch', function (event) { var request = event.request; if (doesRequestAcceptHtml(request)) { event.respondWith( fetch(request).catch(function () { return caches.match('/offline-page'); }) ); } else { event.respondWith( caches.match(request) ); } });

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 text

Cache first, then network

Slide 45

Slide 45 text

self.addEventListener('fetch', function (event) { var request = event.request; if (doesRequestAcceptHtml(request)) { event.respondWith( fetch(request).catch(function () { return caches.match('/offline-page'); }) ); } else { event.respondWith( caches.match(request).then(function (response) { return response || fetch(request); }) ); } });

Slide 46

Slide 46 text

4

Slide 47

Slide 47 text

. Updating the crossword 4

Slide 48

Slide 48 text

var version = 1; var cacheNameSuffix = 'static' + '-' + version; var getISODate = function () { return new Date().toISOString().split('T')[0]; }; var getCacheName = function () { return getISODate() + '-' + cacheNameSuffix; }; var isLatestCacheName = function (key) { return key === getCacheName(); }; var deleteOldCaches = function () { var getOldCacheKeys = function () { return caches.keys().then(function (keys) { return keys.filter(function (key) { return !isLatestCacheName(key); }); }); }; return getOldCacheKeys().then(function (oldCacheKeys) { return Promise.all(oldCacheKeys.map(function (key) { return caches.delete(key); })); }); }; var isCacheUpdated = function () { return caches.keys().then(function (keys) { return keys.some(isLatestCacheName); }); }; isCacheUpdated().then(function (isUpdated) { if (!isUpdated) { updateCache().then(deleteOldCaches); } }); //

Slide 49

Slide 49 text

No content

Slide 50

Slide 50 text

Future usages of service worker on theguardian.com • Offline page will increase in significance • Offline page can be extended • show stale content, like native apps • show personalised content, downloaded ahead of time • show content that has been “saved for later” • Go fully offline-first

Slide 51

Slide 51 text

Offline-first • Render as much as possible without the network • Instantly respond to navigations with a “shell” • Improves the experience for users with poor connections • No more white screen of death • Show stale content whilst fetching new content

Slide 52

Slide 52 text

No content

Slide 53

Slide 53 text

No content

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 text

No content

Slide 56

Slide 56 text

Problems and caveats • Browser bugs in both Chrome and Firefox • Interleaving of versions in CDN cache

Slide 57

Slide 57 text

service-worker.js v1.css offline-page.html caches caches depends on

Slide 58

Slide 58 text

0 60 120 Seconds /v1.css TTL: 1 year /offline-page.html TTL: 60 seconds /service-worker.js TTL: 60 seconds v1 v2 v1 v2

Slide 59

Slide 59 text

0 60 120 Seconds /v1.css TTL: 1 year /v2.css TTL: 1 year /offline-page.html TTL: 60 seconds /service-worker.js TTL: 60 seconds v1 v2 v1 v2 Deploy

Slide 60

Slide 60 text

service-worker.js v2.css offline-page.html v2 v1 v2 v1.css v1 caches caches depends on

Slide 61

Slide 61 text

// /offline-page.json { "html": "", "assets": ["/v1.css"] } Solution: cache manifest

Slide 62

Slide 62 text

Why? Is this valuable? • Fun • Insignificant usage due to HTTPS/browser support • … but good to plant the seed • Iron out browser bugs, pushes the web forward

Slide 63

Slide 63 text

“If we only use features that work in IE8, we're condemning ourselves to live in an IE8 world.” — Nolan Lawson

Slide 64

Slide 64 text

Conclusion • Service workers allow us to progressively enhance the experience for: • offline users • users with poor connections • It’s easy to build an offline page • A simple offline page is a good place to start

Slide 65

Slide 65 text

Further reading • https://www.theguardian.com/info/developer-blog/2015/nov/04/ building-an-offline-page-for-theguardiancom • https://github.com/slightlyoff/ServiceWorker/blob/master/explainer.md • https://www.theguardian.com/service-worker.js

Slide 66

Slide 66 text

Thank you Like what we’re doing? developers.theguardian.com @OliverJAsh

Slide 67

Slide 67 text

No content