[1C1]Service Workers

26
Service Workers Bring your own magic

description

DEVIEW 2014 [1C1]Service Workers

Transcript of [1C1]Service Workers

  • 1. Service Workers Bring your own magic
  • 2. Jungkee Song Github: https://github.com/jungkees Twitter: @jungkees Google+: +JungkeeSong Facebook: https://www.facebook.com/jungkees See the animated version here!
  • 3. Service Workers solve Offline Usage Offline-first Sorry, no magic. Create your own! Programmable cache control Write your own HTTP request proxy Background Processing Wanna do things while your browser is not running? Push messages, System alarm, BackgroundSync
  • 4. Standard W3C first published working draft
  • 5. Standard Please check out the editors draft! https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html https://github.com/slightlyoff/ServiceWorker
  • 6. Principles and terms Runs on same origin Registration keyed by URL scope Document is controlled by matching SW upon navigation Installed worker is considered worker in waiting Lifecycle events: install, activate Functional events: fetch and more to come
  • 7. Are you online? Page Navigation/Resource request Network fetch Response
  • 8. Are you sufficiently online? Page Navigation/Resource request Network fetch 4XX 5XX Timeout DNS failure
  • 9. Offline-first Have a Service Worker? fetch event Navigation/Resource request onfetch Page SW e.respondWith! (Promise) Promise Cache self.caches.match(url) IDB new Response({! status: 200,! body: { }! })
  • 10. Offline-first Fallback to network with SW fetch event Navigation/Resource request onfetch Page SW Cache self.fetch(request) e.respondWith! (Promise) Promise rejects self.caches.match(url)
  • 11. Event-driven worker Browsers are allowed to kill SW at any time Page Page fetch event Navigation/Resource request Navigation/Resource request onfetch Page SW e.respondWith! (Promise) Promise Cache self.caches.match(url) fetch event e.respondWith! (Promise)
  • 12. Registration In the page [ Registration map ] Scope Script URL / /assets/v1/serviceworker.js // scope defaults to "/" ! navigator.serviceWorker.register("/assets/v1/serviceworker.js").then(! function(registration) { ! console.log("success!"); ! registration.installing.postMessage(Howdy from your installing page."); ! // To use the serviceWorker immediately, you might call! // window.location.reload() ! }, function(why) { ! console.error("Installing the worker failed!", why); ! });
  • 13. Registration In the page [ Registration map ] Scope Script URL / sw.js /foo/ /foo/sw.js navigator.serviceWorker.register("/sw.js"); /bar/sw.js navigator.serviceWorker.register("/foo/sw.js", { scope: /foo/ }); navigator.serviceWorker.register("/bar/sw.js");
  • 14. Installation Registration triggers installation of the SW Browser fires install event to the installing SW Event handlers may extend the lifetime of SW for preparing its caches
  • 15. Installation: oninstall In the SW context // caching.js! this.addEventListener("install", function(e) {! e.waitUntil(! // Create a cache and add resources! caches.create(shell-v1).then(function(cache) {! cache.addAll([! "/app.html",! "/assets/v1/base.css",! "/assets/v1/app.js",! "/assets/v1/logo.png",! "/assets/v1/intro_video.webm"! ])! })! );! });
  • 16. Programmable cache control Via Cache / CacheStorage interfaces [Constructor]! interface Cache {! Promise ! match((Request or ScalarValueString) request, optional CacheQueryOptions options);! Promise> ! matchAll((Request or ScalarValueString) request, optional CacheQueryOptions options);! Promise! add((Request or ScalarValueString) request);! Promise> ! addAll(sequence requests);! Promise! put((Request or ScalarValueString) request, Response response);! Promise ! delete((Request or ScalarValueString) request, optional CacheQueryOptions options);! Promise>! keys(optional (Request or ScalarValueString) request, optional CacheQueryOptions options);! }; caches.create(myCache).then(function(cache) { })
  • 17. Have a controller yet? Worker in waiting Once self.oninstall ends So to speak, the installation is successfully done Not yet controlling the document in scope navigator.serviceWorker.controller When all the documents in scope unload The worker in waiting becomes active worker event.replace() works
  • 18. Handle a fetch: onfetch In the SW context this.addEventListener("fetch", function(e) {! // No "onfetch" events are dispatched to the ServiceWorker until it! // successfully installs.! ! // All operations on caches are async, including matching URLs, so we use! // Promises heavily. e.respondWith() even takes Promises to enable this:! e.respondWith(! caches.match(e.request).catch(function() {! return e.default();! }).catch(function() {! return caches.match("/fallback.html");! })! );! });
  • 19. Fetch: navigation request Document selects SW registration upon navigation Page Navigate to https://example.com/index.html [ Registration map ] Scope Script URL onfetch sw.js e.respondWith! (Promise) Promise Cacheself.caches.match(url) / /sw.js /foo/ /foo/sw.js fetch event Scope matching Run SW
  • 20. Subresource request Document uses selected SW registration for subresources [ Registration map ] Scope Script URL onfetch sw.js e.respondWith! (Promise) Promise Cache self.caches.match(url) / /sw.js /foo/ /foo/sw.js Page Fetch https://example.com/img/flower.png fetch event Control Run SW
  • 21. Updating triggered by Registration Browser automatically Successful navigation matching API in worker context: self.update()
  • 22. Updating Document uses selected SW registration for subresources [ Registration map ] Scope active onfetch sw-v2 e.respondWith! (Promise) Promise Cache self.caches.match(url) / v1 fetch event - waiting sw-v1 [[Update]] [[Install]] Page sw-v1 /sw-v2 /-sw-v2 Page v2 Fetch https://example.com/img/flower.png Run SW
  • 23. Security Origin relativity Cross origin resource HTTPS-only Protect end users from man-in-the-middle attacks Existing playground services (e.g. github.io) now work with HTTPS HTTPS is coming across much more of the web quickly Devtools can loosen the restriction for development
  • 24. Performance Event-driven workers Free to shutdown the worker when handlers done Write your workers as though they will die after every request Keep the onactivate short Platform considerations Enhance matching navigation Events implicitly filter Enhance startup
  • 25. Is it ready for you? Chrome 35+ Partial under flag chrome://flags/enable-service-worker Firefox nightly Under consideration IE Partial under flag about:config > dom.serviceWorkers.enabled Stay alerted! Jakes Is ServiceWorker ready?
  • 26. References and practices Service Worker - first draft published - Jake Archibald Specification Githubs explainer Githubs implementation considerations