Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Service Workers, Beyond the Web Page

Service Workers, Beyond the Web Page

Doug Miller

March 02, 2017
Tweet

Other Decks in Technology

Transcript

  1. Service Workers, Beyond the Web Page Doug Miller Software Engineer

    2, Citrix [email protected] Triangle Front-End Developers - 03.02.2017
  2. What is a service worker? Google A service worker is

    a script that your browser runs in the background, separate from a web page, opening the door to features that don't need a web page or user interaction. MDN A service worker is an event-driven worker registered against an origin and a path. W3C Service workers are a new browser feature that provide event-driven scripts that run independently of web pages.
  3. Browser Support Chrome Firefox Safari Edge Opera Basic Support ✔

    ✔ ✔ Offline ✔ ✔ ✗ ✗ ✔ Push Subscription ✔ ✔ ✗ ✗ ✔ Background Sync ✔ ✗ ✗ ✗ ✗
  4. Service Worker Lifecycle 1. Install: ran once per service worker.

    2. Activate: Ran when your service worker is ready to control clients 3. Idle: Active and waiting for events from controlled clients 4. Terminated: Enters this state when not being used. No global state.
  5. Registering a Service Worker if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/serviceWorker.js')

    .then(reg => console.log('SW registered!', reg)) .catch(err => console.log('Curses!', err)); }
  6. Basics of Offline with Service Workers APIs » Cache »

    Fetch Strategies » Cache Only » Network Only » Cache, network fallback » Cache & Network Race » Network fall back to cache
  7. Cache const currentCache = 'mysite-v1'; self.addEventListener('install', (event) => { event.waitUntil(

    caches.open(currentCache).then((cache) => { return cache.addAll([ '/css/styles.css', '/css/fonts/myfont.woff', '/js/common.js', '/js/app.js', ]); }) ); }); serviceWorker.js
  8. Cache self.addEventListener('fetch', (event) => { event.respondWith( caches.open(currentCache).then((cache) => { return

    cache.match(event.request).then((response) => { return response || fetch(event.request).then((response) => { // Optionally add the response to the cache cache.put(event.request, response.clone()); return response; }); }); }) ); }); serviceWorker.js
  9. Cache self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((cacheNames) => { return

    Promise.all( cacheNames .filter(cacheName => cacheName !== currentCache) .map(cacheName => caches.delete(cacheName)); ); }) ); }); serviceWorker.js
  10. Tools to make your life easier » SWPrecache - Github

    » Simplifies precaching assets to enable offline support » SWToolbox - Github » Simplifies adding other caching strategies. » SWPrecacheWebpackPlugin - Github » Webpack wrapper for SWPrecache. Supports addtional caching with SWToolbox. » GruntSWPrecache - BitBucket » Grunt wrapper for SWPrecache.
  11. Cache navigator.serviceWorker.ready .then((registration) => { return registration.pushManager.subscribe({ userVisibleOnly: true });

    }) .then((subscription) => { console.log('Subscribed', subscription.endpoint); return fetch('register', { method: 'post', headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ endpoint: subscription.endpoint }) }); }); app.js
  12. self.addEventListener('pushsubscriptionchange', (event) => { console.log('Subscription expired'); event.waitUntil( self.registration.pushManager.subscribe({ userVisibleOnly: true

    }) .then((subscription) => { console.log('Subscribed after expiration', subscription.endpoint); return fetch('register', { method: 'post', headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ endpoint: subscription.endpoint }) }); }) ); }); serviceWorker.js
  13. Resources » MDN - API » Google - Getting Started

    » SWCookbook - Samples/Demos » OfflineCookbook - Offline strategies » IsServiceWorkerReady - Service worker status » Push Notifications - Push notification walkthrough » Background Sync - Background Sync walkthrough » Lifecycle - Service worker lifecycle