Slide 1

Slide 1 text

Building an Offline Page for theguardian.com Oliver Joseph Ash – London Web Perf, March 2016
 @OliverJAsh

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

web vs native

Slide 5

Slide 5 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 6

Slide 6 text

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

Slide 7

Slide 7 text

We can do better!

Slide 8

Slide 8 text

/developer-blog

Slide 9

Slide 9 text

How it works

Slide 10

Slide 10 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 • geofencing • Trusted origins only (HTTPS, localhost) • Chrome and Firefox stable

Slide 11

Slide 11 text

www.theguardian.com https://

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

1 2

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 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()); }); 2. Get ready with install • install event: get ready! • Cache the assets needed later • Version the cache

Slide 17

Slide 17 text

1 2

Slide 18

Slide 18 text

3. Intercept requests with fetch

Slide 19

Slide 19 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 20

Slide 20 text

No content

Slide 21

Slide 21 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 22

Slide 22 text

HTML

Slide 23

Slide 23 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 24

Slide 24 text

Network first

Slide 25

Slide 25 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 26

Slide 26 text

Assets

Slide 27

Slide 27 text

No content

Slide 28

Slide 28 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 29

Slide 29 text

Cache first

Slide 30

Slide 30 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) { response || fetch(request); }) ); } });

Slide 31

Slide 31 text

4. Updating the crossword

Slide 32

Slide 32 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 33

Slide 33 text

No content

Slide 34

Slide 34 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 35

Slide 35 text

Offline-first • Instantly respond to navigations with a “shell” • Show stale content while revalidating • Improves the experience for users with poor connections

Slide 36

Slide 36 text

No content

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

Conclusion • Service workers allow us to: • define rich experiences for users who are offline • improve performance for users with poor connections • It’s easy to build an offline page • Offline page is a good place to start

Slide 42

Slide 42 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 43

Slide 43 text

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