Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.

Service workers

74 vues

Publié le

Practical introduction into Service Workers. The code is here: https://github.com/uhop/service-worker-demo

Publié dans : Logiciels
  • Soyez le premier à commenter

  • Soyez le premier à aimer ceci

Service workers

  1. 1. Service Workers Practical introduction. Eugene Lazutkin, 4/3/2018, ClubAJAX, Dallas, TX
  2. 2. Abstract Introduction. Prerequisites. Where is it supported? Common techniques. Code & demo.
  3. 3. What is it? It is a client-side proxy server. It is a Worker. Completely asynchronous. API is Promise-based. Uses a special cache.
  4. 4. What can it do? It can: Pre-cache intelligently. Cache strategies. Generate content. Redirect.
  5. 5. What can it do? It can: Work offline. Send and receive messages. Support push. Sync in background.
  6. 6. What can it do? It can: Intercept all I/O in scope. Process received data. Slice & dice… We are not going to touch push nor sync.
  7. 7. Prerequisites: lambda Not necessary but used in this presentation. It is a short-cut for a function.
  8. 8. Prerequisites: lambda var f = function (x) {...}; // equivalent: const f = x => {...};
  9. 9. Prerequisites: lambda var f = function (x, y) {...}; // equivalent: const f = (x, y) => {...};
  10. 10. Prerequisites: lambda var f = function (x, y) { return x + y; }; // equivalent: const f = (x, y) => x + y;
  11. 11. Prerequisites: Promise Promise encapsulates asynchronous actions, like I/O. Super-simple callback-based API. Can be composed.
  12. 12. Prerequisites: Promise promise.then(data => { console.log(data); return data; }).then(data => data + 1).catch( error => console.error(error));
  13. 13. Prerequisites: Promise Promise.all([p0, p1]).then(array => { console.log(array[0], array[1]); }).catch(error => console.error(error));
  14. 14. Prerequisites: fetch() Based on Promise. Replaces XMLHttpRequest.
  15. 15. Prerequisites: fetch() fetch(url, options). then(data => data.json()). catch(error => console.log(error));
  16. 16. Support All new browsers. Including Edge (preview). Including Safari. Excluding IE. Desktop & mobile.
  17. 17. Support Is Service Worker ready?
  18. 18. How to detect? // in an HTML page: if ('serviceWorker' in navigator) { // supported } else { // not supported }
  19. 19. Are controlled by SW already? // in an HTML page: const sw = navigator.serviceWorker. controller; if (sw) {/* yes */} else {/* no */}
  20. 20. Register SW // in an HTML page: navigator.serviceWorker. register('sw.js', {scope: './'}). then(registration => { // we are registered now });
  21. 21. Now what? Our SW can intercept all I/O. fetch() XHR Images …
  22. 22. Now what? We can update our SW on demand. Browser will check SW at least once every 24 hours, if possible. Prevents possible update bugs. Cache is bypassed.
  23. 23. Now what? First installation of SW will require a refresh. The rest can seamlessly switch for new clients. Or retake all clients.
  24. 24. SW internals An event-driven JS. install, activate, fetch, message… Uses a special global space.
  25. 25. SW: install self.addEventListener('install', event => { // precache event.waitUntil( // waits a promise caches.open('v1').then(cache => cache.addAll(['./log.js']) ).then(() => self.skipWaiting()) ); });
  26. 26. SW: activate self.addEventListener('activate', event => { // remove old caches event.waitUntil(cleanOldCaches); });
  27. 27. SW: activate const cleanOldCaches = () => caches.keys().then(names => Promise.all(names. filter(name => name !== 'v1'). map(name => caches.delete(name))) ).then(() => self.clients.claim());
  28. 28. SW: fetch self.addEventListener('fetch', event => event.respondWith( fetch(event.request) ) );
  29. 29. SW: fetch self.addEventListener('fetch', e => event.respondWith(caches.open('v1'). then(c => c.match(e.request)). then(d => d || fetch(e.request)) ));
  30. 30. SW: fetch self.addEventListener('fetch', e => event.respondWith(new Response( '{"a": 1, "b": true, "c": []}', {headers: {'content-type': 'application/json'} }));
  31. 31. Send a message // in an HTML page: navigator.serviceWorker. controller.postMessage('Hello!');
  32. 32. SW: message self.addEventListener('message', e => { console.log('From:', e.source.id); console.log('Data:', e.data); });
  33. 33. Message Both page and SW can send and receive messages at will.
  34. 34. Code & Demo https://github.com/uhop/service-worker- demo
  35. 35. Useful links MDN: Using Service Workers The Offline Cookbook By Jake Archibald! ServiceWorkers cookbook Understanding Service Workers Ember examples at the end!
  36. 36. That’s all, folks!

×