Service Worker Internals ~{@saket_kmr} & {@piyuesh23} Who we - - PowerPoint PPT Presentation

service worker internals
SMART_READER_LITE
LIVE PREVIEW

Service Worker Internals ~{@saket_kmr} & {@piyuesh23} Who we - - PowerPoint PPT Presentation

Service Worker Internals ~{@saket_kmr} & {@piyuesh23} Who we are? @saki007ster @piyuesh23 Technical Architect, QED42 UI/UX Lead, QED42 Agenda Mobile Web Vs Mobile Apps PWA & Service worker introduction Service worker


slide-1
SLIDE 1

~{@saket_kmr} & {@piyuesh23}

Service Worker Internals

slide-2
SLIDE 2

Who we are?

@piyuesh23 Technical Architect, QED42 @saki007ster UI/UX Lead, QED42

slide-3
SLIDE 3

Agenda

  • Mobile Web Vs Mobile Apps
  • PWA & Service worker introduction
  • Service worker dive-in
  • Basic Caching strategies
  • Tooling & debugging
  • Demo
slide-4
SLIDE 4

V S

Mobile Web Mobile Apps

slide-5
SLIDE 5

67%

33%

slide-6
SLIDE 6
slide-7
SLIDE 7
slide-8
SLIDE 8

?

slide-9
SLIDE 9

Tabbed Experience

slide-10
SLIDE 10

Offline Enabled

slide-11
SLIDE 11

Notifications

Simple Notifications Push Messages
slide-12
SLIDE 12

Branding

slide-13
SLIDE 13

And Many More...

slide-14
SLIDE 14
  • 08/2010
  • http://www.wired.

com/2010/08/ff_webrip/

The Web is Dead

slide-15
SLIDE 15
  • 02/2014
  • http://www.wired.

com/insights/2014/02/web- dead/

The Web is Not Dead

slide-16
SLIDE 16

Progressive Web Apps

  • Good Experience on flaky network

connections

  • Fast Loading
  • Obscure branding via splash screens
  • Installable
  • Push notifications
  • 1-click away from accessing content
slide-17
SLIDE 17
slide-18
SLIDE 18

Introduction to Service Workers

slide-19
SLIDE 19

Features

Offline Web

Background processing

Programmable cache

Functional in case of slow connections

Geo-fencing Push Notifications 2G EDGE
slide-20
SLIDE 20

https-only

slide-21
SLIDE 21

Pillars of SW

slide-22
SLIDE 22

Working With Service Workers

slide-23
SLIDE 23

Installing Idle Error Activate Terminated Fetch / Message

No service worker

slide-24
SLIDE 24
slide-25
SLIDE 25
slide-26
SLIDE 26

Step 1: Registering a service worker

if ('serviceWorker' in Navigator) { navigator.serviceWorker.register('/sw.js', { scope: './' }).then(function(reg) { // registration worked console.log('Registration succeeded. Scope is ' + reg.scope); }).catch(function(err) { // Registration failed. console.log('Registration failed with ' + error); }); }

Check for Browser Support Scope for serviceWorker to

  • perate upon.

Default scope is set to the location of sw.js file. Navigator.serviceWorker. controller specified the worker controlling a page.

slide-27
SLIDE 27 self.addEventListener('install', function(event) { console.log('[install] Kicking off server worker registration.'); event.waitUntil( // pre-fetch app-shell & perform initialization steps ); }); self.addEventListener('activate', function(event) { // Anything needed to be done before activation. e.g., cleanup old cache. });

App-shell: minimal HTML,

CSS, and JavaScript powering a user interface

Install: pre-cache & app- initialization Activate: Mostly useful in case of SW updates. Cleanup of old cache.

slide-28
SLIDE 28 self.addEventListener('fetch', function(event) { // Intercept requests going to Network. // Mostly useful to return data from cache or cache // network response. });
slide-29
SLIDE 29

Basic Cache-ing Strategies

slide-30
SLIDE 30
  • Most useful for single page websites or

places where data/app are separate.

  • Cache content offline while installing

service worker.

  • Request gets served from Service

worker cache(when offline).

  • Request served from internet(when
  • nline) - caching response.
slide-31
SLIDE 31 var cacheName = 'DCON NOLA'; var staticResources = [ '/script.js', '/style.css' ]; self.addEventListener('install', function(event) { event.waitUntil( cache.open(cacheName).then(function(cache) { return cache.addAll(staticResources); }); ); })

Wait before activation until app-shell is cached.

{

App-Shell

slide-32
SLIDE 32 self.addEventListener('fetch', function(event) { event.respondWith(serverFromCache(event.request)); }); function serveFromCache(request) { caches.match(request).then(function(response)) { return response; }).catch(function(err) { return caches.match('/offline.html'); }) }

respondWith() receives

  • nly a valid response
  • bject.

navigator checks for the

  • network. returns true or

false.

slide-33
SLIDE 33 function serverFromNetwork(event) { caches.open(cacheName).then(function(cache) { return fetch(event.request.url).then(function (response) { cache.put(event.request.url, response.clone()); return response; }).catch(function(err) { return cache.match(event.request.url).then(function (response) { return response; }); }); }) }

Fetch response from network & update cache Response object is a readable stream object & can be consumed only once(either to update cache or respond back). If something goes wrong with the network fetch, respond back with a stale copy from cache.

slide-34
SLIDE 34

Got another custom scenario/Handling cache busting...

slide-35
SLIDE 35
slide-36
SLIDE 36 var jsBucket = 'JS'; var cssBucket = 'CSS'; var cssResources = [ '/slides.css', '/styles.css' ]; var jsResources = [ '/slides.js', '/scripts.js' ];

Break down Css & Js assets into different cache buckets.

slide-37
SLIDE 37 self.addEventListener('install', function(event) { console.log('[install] Kicking off server worker registration.'); event.waitUntil( caches.open(cssBucket).then(function(cache) { cache.addAll(cssResources); }); caches.open(jsBucket).then(function(cache) { cache.addAll(jsResources); }); ); });

Avoid overhead for sw.js check

  • n each page using http cache-

control headers.

slide-38
SLIDE 38 self.addEventListener('activate', function(event) { var cacheWhiteList = [jsBucket, cssBucket]; event.waitUntil(function(caches) { return Promise.all( caches.map(function(cache) { if (cacheWhileList.indexOf(cache) == -1) { return caches.delete(cache); } }) ); }) })

Activate fired after installing the service worker and all the current versions of sw are closed. Use event.replace() inside the install event for the installing service worker to take effect instantly.

slide-39
SLIDE 39 40+ 27+ 44+

Need to support a browser that isn’t ready, Don’t worry we got you covered Browser Support

slide-40
SLIDE 40

Tooling & debugging

slide-41
SLIDE 41

chrome://serviceworker-internals/

slide-42
SLIDE 42

Local development without ssl-certificates

./Google\ Chrome --user-data-dir=/tmp --ignore- certificate-errors --unsafely-treat-insecure-origin-as- secure=http://dcp.16

slide-43
SLIDE 43

Network requests

slide-44
SLIDE 44

Chrome devtools

slide-45
SLIDE 45
  • navigator.serviceWorker.register('my-service-worker.js');
  • global.toolbox.options.debug = true

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

// The route for any requests from the googleapis
  • rigin
toolbox.router.get('/(.*)', global.toolbox. cacheFirst, {
  • rigin: /\.googleapis\.com$/
});
slide-46
SLIDE 46

Common use-cases

Caching requests for authenticated users: Caching cross-origin resources:

fetch(url, {credentials: true}).then(function (response){ // Request will be sent to the server with cookies. }) fetch(url, {mode: ‘no-cors’}).then(function (response){ // The response will be opaque i.e., we would never know if // the request was successful. })
slide-47
SLIDE 47

DEMO

slide-48
SLIDE 48

Use-case:

  • Drupal Camp Pune website
  • Allow users to access the website offline
  • Provide an app-like experience
  • Allow users to add sessions to their schedule even when they are offline.
  • Redirect pages that are not cached to an offline fallback page.
slide-49
SLIDE 49

Drupal Enhancements:

  • Custom route for returning lis to aggregated assets: /css-
js-aggregated.json
  • Custom route for adding/removing schedule flag:
/schedule/{entity_id}/{action}/{uid}
  • Rest endpoints for session & sponsor nodes: /sessions.
json & /sponsors.json
  • hook_page_attachments_alter() to handle loading of
service worker js & manifest.json(for PWA) files.

Cache-strategies:

  • Offline first
  • Network first
  • Slow connection:

Again offline first approach would fit in here.

  • Offline page:

Redirect users to an offline page showing some info about the event, asking them to go online for viewing details

slide-50
SLIDE 50

Resources

slide-51
SLIDE 51

So How Was It? - Tell Us What You Think Thanks!