Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Web optimization with service woker

5,363 views

Published on

Sharing how to using Service Worker to help web speed up with less requests and smaller transferred sizes.

Published in: Software
  • Be the first to comment

  • Be the first to like this

Web optimization with service woker

  1. 1. Web Optimization with ServiceWoker Blackie Tsai blackie.tsai@xuenn.com 06/06/2017
  2. 2. Agenda Introduction to ServiceWorker Strategy for ServiceWorker sw-toolbox Result Comparison
  3. 3. Introduction to ServiceWorker
  4. 4. • Service worker is a programmable network proxy, allowing you to control how network requests from your page are handled. • It's a JavaScript Worker, so it can't access the DOM directly. Instead, a service worker can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM if needed. • Host server need use SSL • Cache request MUST trigger under register routing path What is ServiceWorker
  5. 5. SSL and Cache Scope
  6. 6. • Browser support. • http://caniuse.com/#feat=serviceworkers • Jake Archibald's is Serviceworker ready site. • Need HTTPS Prerequisites
  7. 7. The service worker life cycle
  8. 8. • On install - as a dependency • On install - not as a dependency • On activate • On user interaction • On network response • Stale-while-revalidate • On push message • On background-sync When to store resources
  9. 9. On install - as a dependency self.addEventListener('install', function(event) { event.waitUntil( caches.open('mysite-static- v3').then(function(cache) { return cache.addAll([ '/css/whatever-v3.css', '/css/imgs/sprites-v6.png', '/css/fonts/whatever-v8.woff', '/js/all-min-v4.js' // etc ]); }) ); });
  10. 10. On install - not as a dependency self.addEventListener('install', function(event) { event.waitUntil( caches.open('mygame-core- v1').then(function(cache) { cache.addAll( // levels 11-20 ); return cache.addAll( // core assets & levels 1-10 ); }) ); });
  11. 11. On active self.addEventListener('activate', function(event) { event.waitUntil( caches.keys().then(function(cacheNames) { return Promise.all( cacheNames.filter(function(cacheName) { // Return true if you want to remove this cache, // but remember that caches are shared across // the whole origin }).map(function(cacheName) { return caches.delete(cacheName); }) ); }) ); });
  12. 12. On user interaction document.querySelector('.cache- article').addEventListener('click', function(event) { event.preventDefault(); var id = this.dataset.articleId; caches.open('mysite-article-' + id).then(function(cache) { fetch('/get-article-urls?id=' + id).then(function(response) { // /get-article-urls returns a JSON- encoded array of // resource URLs that a given article depends on return response.json(); }).then(function(urls) { cache.addAll(urls); }); }); });
  13. 13. On network response self.addEventListener('fetch', function(event) { event.respondWith( caches.open('mysite- dynamic').then(function(cache) { return cache.match(event.request).then(function (response) { return response || fetch(event.request).then(function(res ponse) { cache.put(event.request, response.clone()); return response; }); }); }) ); });
  14. 14. Stale-while-revalidate self.addEventListener('fetch', function(event) { event.respondWith( caches.open('mysite- dynamic').then(function(cache) { return cache.match(event.request).then(function(r esponse) { var fetchPromise = fetch(event.request).then(function(net workResponse) { cache.put(event.request, networkResponse.clone()); return networkResponse; }) return response || fetchPromise; }) }) ); });
  15. 15. Strategy for ServiceWorker
  16. 16. • Cache only • Network only • Cache, falling back to network • Cache & network race • Network falling back to cache • Cache then network • Generic fallback • ServiceWorker-side templating Serving suggestions
  17. 17. Performance impact of ServiceWorker Demo : Trained-to-thrill
  18. 18. • Cache on install, for the static UI and behaviour • Cache on network response, for the Flickr images and data • Fetch from cache, falling back to network, for most requests • Fetch from cache, then network, for the Flickr search results Demo uses
  19. 19. sw-toolbox
  20. 20. • sw-toolbox is a collection of tools for service workers, create by Google • Install • npm install --save sw-toolbox • Register your service worker • navigator.serviceWorker.register('my-service-worker.js’); • Add Service Worker Toolbox to your service worker script • importScripts('node_components/sw-toolbox/sw-toolbox.js'); sw-toolbox
  21. 21. • toolbox.networkFirst • toolbox.cacheFirst • toolbox.fastest • toolbox.cacheOnly • toolbox.networkOnly Handlers
  22. 22. • Router related • toolbox.router.<get|post|put|delete|head>(urlPattern, handler, options) • toolbox.router.any(urlPattern, handler, options) • toolbox.router.default • Cache related • toolbox.precache(arrayOfURLs) • toolbox.cache(url, options) • toolbox.uncache(url, options) Methods
  23. 23. • ResourceCDN(maxEntries: 100, maxAgeSeconds: 1200) • https://<CDNDomain>/Public/* • ContentCDN(maxEntries: 20, maxAgeSeconds: 1800) • https://<CDNDomain>/ContentCDN/* • Betgenius(maxEntries: 5, maxAgeSeconds: 600) • https://<BetgeniusDomain>/* • WebAppLocal(maxEntries: 10, maxAgeSeconds: 1200) • https://<WebAppDomain>/Public/Lib/* Recommend Setting
  24. 24. Setup Overview service-worker-init.js sw-toolbox.js Site.Master ResourceCDN Betgenius ContentCDN (HomepageCDN) WebAppLocal /Public/Lib • https://<cdn>/Public/JS/Language/en- gb.js?v=07130719 • https://<cdn>/Public/bundles/js/coreJ s.js?v=07130719 • https://<cdn>/Public/bundles/js/react .js?v=07130719 • …. • https://<betgenius>/188BetFlash- phase3/api.js • https://< betgenius>/188BetFlash- phase3/swfobject.js • https://<cdn>/ContentCDN/Football/ Sport01.jpg?v=143 • https://<cdn>/ContentCDN/Football/ Sport02.jpg?v=143 • https://<cdn>/ContentCDN/Football/ Sport03.jpg?v=143 • … • https://<cdn>/Public/Templates/OddsPage/en -gb.Football_AHOU.html?v=07130719 • …
  25. 25. Sample Code Site.Master
  26. 26. Sample Code Service-worker.init.js
  27. 27. Chrome Verification Network Tab
  28. 28. Chrome Verification Application Tab
  29. 29. Result Comparison
  30. 30. Before
  31. 31. After Service-worker First Time Loading
  32. 32. After Service-worker Second time(exclude vendor)
  33. 33. After Service-worker Second time(include vendor)
  34. 34. • React Worker Dom • Github : web-perf/react-worker-dom • Performance Demo : React Worker Dom Another optimization from Web Worker
  35. 35. • Service Workers: an Introduction • Jake Archibald - The offline cookbook • Making a Simple Site Work Offline with ServiceWorker References
  36. 36. Q & A
  37. 37. 11F., No.399, Ruiguang Rd., Neihu Dist., Taipei City 114, Taiwan THANK YOU! Xuenn +886 2 2798 8529 +886 2 2798 8531 www.xuenn.com YiTeng +886 2 2659 8958 +886 2 2659 8956 www.yitmh.com

×