[Ewa Gasperowicz] Caching strategies and their performance footprint

[Ewa Gasperowicz] Caching strategies and their performance footprint

Content level: Intermediate

Does your site need a performance boost? With Service Worker supported in all main browsers, you can up your game with precise caching behaviors and management. Network requests use time and bandwidth. Caching resources take valuable storage space. Let’s discuss how to strike a balance between the two with some fine-tuned caching strategies.

Ewa Gasperowicz
Google / Switzerland

3a6de6bc902de7f75c0e753b3202ed52?s=128

Google Developers Group Lviv

October 12, 2018
Tweet

Transcript

  1. Caching strategies And their performance footprint Ewa Gasperowicz Developer Programs

    Engineer, Google
  2. #dfua Online, offline and Lie-Fi

  3. #dfua Online, offline and Lie-Fi

  4. #dfua Online, offline and Lie-Fi

  5. #dfua https://jakearchibald.github.io/isserviceworkerready/

  6. #dfua Service Worker is a proxy ? SW

  7. #dfua Service Worker is a proxy

  8. #dfua Service Worker is a proxy

  9. #dfua Service Worker is a proxy

  10. #dfua Service Worker is a proxy ?

  11. None
  12. No images

  13. No styles

  14. EXIT

  15. #dfua Service Worker makes websites resilient ? SW

  16. So let’s cache

  17. #dfua

  18. #dfua Size is an advantage of PWA

  19. #dfua URL vs Site

  20. #dfua

  21. #dfua

  22. First load

  23. SW installed

  24. Page cached

  25. Page cached

  26. Full site cached

  27. #dfua Be mindful of used resources

  28. Designing SW flow

  29. “ Hope is not a strategy “ - Many people

  30. #dfua Two parts of the strategy SW Caching Routing

  31. Caching

  32. #dfua Caching • WHAT to cache • WHEN to cache

    • How to UPDATE
  33. #dfua Caching • What NOT to cache • WHAT to

    cache • WHEN to cache • How to UPDATE
  34. #dfua Rule #1: cut the fat

  35. #dfua Don’t cache, put in trash! • Oversized or unoptimized

    images • Unnecessary libraries • Non-essential fonts • etc.
  36. “ Not all content is created equal “ - Me

  37. Rich visual experience womentechmakers.comt

  38. womentechmakers.comt Site is unusable

  39. navigation and action womentechmakers.comt branding and priority informative decorative

  40. Selective image strategies Inline, embedded in doc always in cache

    cached at best effort (with limit) fallback (with ALT text)
  41. #dfua When to cache • Precaching • Runtime caching

  42. #dfua Precaching Push assets to cache ahead of time •

    Static assets like styles, scripts, important images • Versioning is important • Updates when the service worker updates
  43. #dfua const version = '15'; self.addEventListener('install', event => { event.waitUntil(

    caches.open(`static-${version}`) .then(cache => cache.addAll([ '/script-e9cght.js', '/style-bhj371e.css', '/banner-45ea2e4.jpg' ])) ); }); SW version # Asset version #
  44. #dfua Precaching pros&cons • Easy and automatable • Good for

    performance • Not for a whole site • Upfront network cost • Possibly caching unnecessary urls • Hard to update unversioned assets
  45. #dfua Runtime Caching Cache resources when they are accessed first

    time • Dynamic content • Non-revisioned content • Updates depending on used strategy • Non-crucial content (e.g. not on critical path)
  46. #dfua self.addEventListener('fetch', function(event) { event.respondWith( caches.open('mycache-runtime').then(cache => { fetch(event.request).then(response =>

    { cache.put(event.request, response.clone()); // ...usually also send response to the page }); }); ); }); Fetch event Cache
  47. #dfua Runtime caching pros&cons • Updates not independent on SW

    • Cache assets in response to user behavior • Asset needs to be fetched first • Site’s storage size grows over time • Need to limit no of entries and expiration policy
  48. Serving

  49. #dfua Serving SW cache custom logic network

  50. #dfua Workbox • CacheFirst • CacheOnly • NetworkFirst • NetworkOnly

    • StaleWhileRevalidate • Custom handler Plugins & Extensions
  51. #dfua Custom handler const FALLBACK_IMAGE_URL = '/images/icons/fallback.svg'; const imagesHandler =

    workbox.strategies.cacheFirst(opts); // Cache images from Cloudinary workbox.routing.registerRoute( new RegExp('https://res.cloudinary.com/pieshop/.*'), ({event}) => { return imagesHandler.handle({event}) .catch(() => caches.match(FALLBACK_IMAGE_URL)); });
  52. navigation and action womentechmakers.comt branding and priority informative decorative

  53. navigation and action // Inline strategy <a href=”https://www.youtube.com/...”> <svg>...</svg> </a>

    Inline
  54. branding and priority // Precache strategy const manifest = [‘images/priority/’,

    ...]; swlib.precache(manifest); Precache
  55. decorative // Runtime cache strategy swlib.strategies.cacheFirst({ cacheName: 'images-cache', cacheExpiration: {maxEntries:

    50}, }); Cache at runtime (with limit)
  56. decorative // Runtime cache strategy swlib.strategies.cacheFirst({ cacheName: 'images-cache', cacheExpiration: {maxEntries:

    50}, }); Cache at runtime (with limit)
  57. informative // Fallback strategy function svgFallback({url}) { const alt =

    url.searchParams.get('alt'); const svg = `<svg><path ... /><text><tspan> ${alt || ''}</tspan></text></svg>`; return new Response(svg, { headers: {'Content-Type': 'image/svg+xml'} }); } Fallback
  58. informative // Fallback strategy function svgFallback({url}) { const alt =

    url.searchParams.get('alt'); const svg = `<svg><path ... /><text><tspan> ${alt || ''}</tspan></text></svg>`; return new Response(svg, { headers: {'Content-Type': 'image/svg+xml'} }); } Fallback (with alt)
  59. #dfua Architecture implications

  60. #dfua Summary • Caching is about resiliency as much as

    offline • Don’t just jump in, have a strategy • Make your site lean • Have proper versioning for static assets • Cache selectively • Control the size of your app over time
  61. #dfua Icons made by: CC 3.0 BY Daniel Bruce

  62. Thank you! Questions? Ewa Gasperowicz Developer Relations Engineer, Google