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

Diving Deep Into Performance Optimization

Diving Deep Into Performance Optimization

The fundamentals to optimize performance of web applications.

Ahmad Alfy

March 20, 2019

More Decks by Ahmad Alfy

Other Decks in Programming


  1. Diving deep into performance Optimization By Ahmad El-Alfy Head of

    software development at Robusta
  2. • My name is Ahmad El-Alfy. • I wrote my

    first HTML document nearly 20 years ago. • Development head and front-end developer at • Facebook Developers Circle Cairo Lead. • Organizer at EgyptJS • Web standards and Accessibility fanatic. @ahmadalfy
  3. We’re Hiring … as usual :) career@robustastudio.com Front-end developers Backend

    Developers (PHP/Rails) Quality Control Engineers Mobile developers
  4. A little back story • We started offering a new

    service we call CTO as a service. • Part of my job was evaluating and profiling a lot of applications and products developed by others. I quickly fell in love with performance audits and investigations.
  5. Our GOAL Today

  6. Agenda • Setting up performance budget • Fundamentals to understand

    performance optimization • Network inside the browser • How the browsers work • Different tools we use to identify problems • Techniques
  7. What is Slow ?

  8. We need metrics we can measure

  9. What metrics we can use? • DOMContentLoaded ? • window.onload

    ? • Frames Per Second ? • Jank ? Layout Thrashing ? • First Pain ?
  10. Our focus primarily was on how much bytes we are

    shipping down the wire and how many requests we are making
  11. https://httparchive.org/reports/page-weight?start=2014_01_01&end=2019_01_01&view=list#bytesTotal

  12. Let’s examine the user’s journey

  13. The RAIL performance goals Touch to paint
 < 100 ms

    Touch to move
 < 16 ms Each frame completes in
 < 16 ms Main thread JS work complete
 < 50 ms / chunk Ready to use
 < 1000 ms https://developers.google.com/web/fundamentals/performance/rail#ux
  14. https://www.youtube.com/watch?v=vOvQCPLkPt4&list=LLyUM7lBkQ_dheU-wh6Q8-Gw&index=2&t=0s

  15. So now we’ve a budget

  16. Let’s talk about how the browsers work

  17. Part 1 - Network

  18. HTTP 1.1 • It’s a 20 years old protocol that

    we’re still using • It suffers from a lot of problems like latency and limitations on transfer size and number of requests. • BUT We were able to overcome that
  19. None
  20. Spriting

  21. Inlining .icon1 { background: url(data:image/png;base64,<data>); } .icon2 { background: url(data:image/png;base64,<data>);

  22. Concatenation

  23. Sharding

  24. Welcome HTTP2

  25. None
  26. https://daniel.haxx.se/http2/http2-v1.9.pdf Multiplexing numerous streams going over a single -TLS- encrypted-

    TCP connection.
  27. Header compression

  28. Prioritization and dependency

  29. Server Push

  30. Demo • httpvshttps.com

  31. Part 2 - Parsing, Downloading and Rendering

  32. None
  33. None
  34. None
  35. CSS • While downloading CSS files, rendering in the web

    page is completely blocked. This is because of a phenomenon called “Progressive Rendering”. Without it, you will see content shifting and changing their style while the assets are being downloaded. • Inline CSS is an exception, it will render immediately after loading.
  36. Images • Images in the HTML is downloaded according to

    the specs: • Images in CSS will be downloaded if it is a part of the render tree
  37. None
  38. None
  39. None
  40. None
  41. None
  42. Script async / defer

  43. Fonts • Font files will only be downloaded if an

    element uses a font that is a part of the render tree and contain text. • This results in the phenomena we call Flash of Unstyled Text and Flash of Invisible Text
  44. None
  45. Now what are the tools we can use for auditing?

  46. Lighthouse A relatively new tool that replaced the de facto

    standard Page Speed Insights. Available in Google Chrome under the tab “Audit” in the DevTools. You can use it to emulate slower network connection or a slow CPU. Available as a command line interface.
  47. Bro Tip: use the CLI • Run much faster than

    the one in the DevTools, can run in headless mode as well. • Isn’t affected by the extensions you have on your Chrome setup. • Save the results in an HTML document with the exact time, date and version of the lighthouse API. • Can be integrated with your CI.
  48. None
  49. None
  50. The report • Images • Origins • Render blocking resources

    • Critical path requests • Text visibility • Main thread work • Cache policy • DOM Size
  51. Images Use the proper image format

  52. Images — cont • Don’t ever use an animated gif,

    change it to a video. • Gifs consume more memory from the browser and they have bigger file size than an equivalent movie.
  53. Images — cont • Start using WebP NOW • Relatively

    new format, invented by Google. It offers 30% compression over the other formats.
  54. None
  55. <picture> <source srcset="img/awesomeWebPImage.webp" type="image/webp"> <source srcset="img/creakyOldJPEG.jpg" type="image/jpeg"> <img src="img/creakyOldJPEG.jpg" alt="Alt

    Text!"> </picture>
  56. Images — cont • LAZY LOAD EVERYTHING • It is

    a term commonly used to describe a technique where we stop image loading until it is visible in the user’s viewport. • It is used heavily in listing to: • Improve user experience • Save the bandwidth
  57. None
  58. None
  59. None
  60. None
  61. Recommended Tool

  62. Images — cont Serve the appropriate image size to the

    right browser
  63. Images — cont Get rid of the meta data

  64. Origins Once the browser find a resource located on another

    origin, it will attempt to open a TCP connection to that new origin to retrieve the data. This technique works by telling the browser ahead that it needs to connect to the following list of origins so that when the browser react the request, most of the handshaking, DNS lookup and the other network stuff have been taken care of
  65. Render blocking requests This is because CSS and JavaScript both

    block the main thread while downloading. The old practice was to move the stylesheet to the top and move the scripts to the bottom. The new recommendation is to inline the CSS used for the critical part (above the fold) and move everything else to the bottom. Scripts should also use the attribute defer or async.
  66. None
  67. Text visibility FOIT block the user for sometime till the

    font is downloaded or it pass the timeout phase of the font loading. We can control the behavior of the font using the property font-display to eliminate the font swapping period and always use a fallback font.
  68. Cache Policy Having a proper cache policy significantly improve subsequent

    visits load. The problem usually arise from third party scripts that have short cache lifetime by default (like GTM, GA … etc) We can always rely on cache busting mechanisms to invalidate the cache
  69. DOM size Google recommends having less than 1500 DOM node.

    Problems usually arise in: • Huge content websites with significant DOM nodes • Using inline SVGs • Serving content for both mobile and desktop and using display none to hide nodes on any platform
  70. Working with videos • Videos should be lazy loaded as

    well and should be properly sized and encoded • If a video is used for presentation only, test the internet connection speed and remove it if it isn’t loading
  71. let videoLoad = new Promise((resolve) => { video.addEventListener('canplaythrough', () =>

    { resolve('can play'); }); }); let videoTimeout = new Promise((resolve) => { setTimeout(() => { resolve('The video timed out.'); }, 2000); }); Promise.race([videoLoad, videoTimeout]).then(data => { if (data === 'can play') { video.play(); setTimeout(() => { video.classList.add('video-loaded'); }, 3000); } else { this.cancelLoad(video); } });
  72. Scrolling and listeners addEventListener(document, "touchstart", (e) => { // Whatever

    }, { passive: true } );
  73. Serve JavaScript modules

  74. Always use a profiling tool

  75. Profiling JavaScript The performance panel can help you profile your

    JavaScript code (identifying the slow parts), detect where the spikes happen (scripting? painting? layout?)
  76. None
  77. None
  78. None
  79. References • Google Chrome Release Notes. • Essential Images Optimization,

    an eBook by Addy Osmani. • Web.Dev; huge resource by Google • Books: High Performance Websites, Even Faster Web Sites. Both by by Steve Souders • Web performance made easy (Google I/O '18)
  80. None