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

Modern Performance Best Practices 2016

Modern Performance Best Practices 2016

Modern Performance Best Practices presented at Velocity 2016

6d9b2c900628962b16a5cb5e4e73990e?s=128

Dustin Whittle

June 21, 2016
Tweet

Transcript

  1. Modern Performance Best Prac0ces Dus$n Whi*le

  2. Dus0n Whi6le dus0nwhi6le.com @dus0nwhi6le San Francisco, California, USA AppDynamics, Kwarter,

    SensioLabs, Yahoo!, …
  3. Modern Performance Best Prac0ces Join this session for a prac$cal

    introduc$on to modern performance best prac$ces for web apps. We will dive into the latest tools and best prac$ces for launching an ideal end-user experience. Find out how you can leverage Chrome Developer Tools, Google PageSpeed, and WebPageTest to get started improving your applica$ons. author twitter handle
  4. Modern Performance Best Prac0ces § Why web performance ma*ers §

    Common performance best prac$ces – Dive into PageSpeed Rules + look at SiteSpeed.io § A refactoring example – We will have an interac$ve refactoring session of an exis$ng app to reach an ideal pagespeed score § Discuss common tools that automate these techniques (ngx_pagespeed, yo*aa, cloudflare, etc) § Dive into WebPageTest to show how to test web performance from any browser § Recap best prac$ces and follow up with resources
  5. This talk is heavily inspired from: Google PageSpeed Rules Google

    Web Fundamentals Ryan Tomayko’s “Things Caches Do” Addy Osmani’s “Automa$ng Workflow” Ilya Grigorik “High Performance Browser Networking”
  6. Please be interac$ve! Ask ques$ons. Engage!

  7. None
  8. None
  9. Login Flight Status Search Flight Purchase Mobile Big data SOA

    NOSQL Cloud Agile Web Application complexity is exploding
  10. Why performance ma*ers

  11. Performance directly impacts the bo*om line

  12. None
  13. How fast is fast enough? §Performance is key to a

    great user experience -Under 100ms is perceived as reac$ng instantaneously -A 100ms to 300ms delay is percep$ble -1 second is about the limit for the user's flow of thought to stay uninterrupted -Users expect a site to load in 2 seconds -ASer 3 seconds, 40% will abandon your site. -10 seconds is about the limit for keeping the user's a*en$on §Modern applica0ons spend more 0me in the browser than on the server-side
  14. Performance Ma*ers • Treat performance as a feature • Implement

    performance best prac$ces on server-side and client-side • Use the 14kb rule and op$mize cri$cal path for instant loading • Implement a responsive design + responsive image strategy • Implemen$ng a touch-first strategy • Using task runners to build and deploy code for produc$on
  15. Scaling server-side applica$ons • Caching - Cache as much on

    the client-side and server side as possible (javascript, css, images, fonts, content). • Leverage a CDN + browser caching • Use a reverse proxy cache on the server side • Queuing - Do not delay the user experience for tasks that can be executed in the background • Async - Op$mize work to execute concurrently / asynchronously
  16. Leverage HTTP Caching • For sta$c components: implement "never expire"

    policy by sejng far future expires header • For dynamic components: use an appropriate Cache-Control header to help the browser with condi$onal requests
  17. None
  18. Expires or Invalida0on

  19. Expira0on

  20. None
  21. None
  22. Valida0on

  23. None
  24. None
  25. Expira0on and Invalida0on

  26. None
  27. None
  28. None
  29. None
  30. Caching Best Practices § Use consistent URLs: if you serve

    the same content on different URLs, then that content will be fetched and stored multiple times. Tip: note that URLs are case sensitive! § Ensure the server provides a validation token (ETag): validation tokens eliminate the need to transfer the same bytes when a resource has not changed on the server. § Identify which resources can be cached by intermediaries: those with responses that are identical for all users are great candidates to be cached by a CDN and other intermediaries. § Determine the optimal cache lifetime for each resource: different resources may have different freshness requirements. Audit and determine the appropriate max-age for each one. § Determine the best cache hierarchy for your site: the combination of resource URLs with content fingerprints, and short or no-cache lifetimes for HTML documents allows you to control how quickly updates are picked up by the client. § Minimize churn: some resources are updated more frequently than others. If there is a particular part of resource (e.g. JavaScript function, or set of CSS styles) that are often updated, consider delivering that code as a separate file. Doing so allows the remainder of the content (e.g. library code that does not change very often), to be fetched from cache and minimizes the amount of downloaded content whenever an update is fetched.
  31. Queueing • Any process that is slow and not important

    for the h6p response should be queued • Sending emails/sms/push no0fica0ons + pos0ng to social accounts • Upda0ng profiles and discovering friends from social accounts • Analy0cs + Instrumenta0on • …
  32. None
  33. None
  34. In modern web applica$ons more latency comes from the client-side

    than the server-side.
  35. Common Performance Best Prac$ces • Reduce # of HTTP Requests

    • Avoid redirects • Concatena$ng resources stylesheets + javascript • Combining images using CSS image sprites • Leverage HTTP caching to eliminate requests
  36. Common Performance Best Prac$ces • Reduce size of HTTP requests

    • Op$mize stylesheets + javascripts + images + fonts • Leverage gzip compression • Reduce cookie size + use cookie less domains for sta$c assets
  37. Common Performance Best Prac$ces • Op$mize content • Move stylesheet

    to head • Move javascript to body close (and eliminate blocking javascript) • Preload components when idle
  38. Common Performance Best Prac$ces • Reduce DNS lookups • Reduce

    network latency with Content Delivery Networks
  39. Google Chrome Developer Tools

  40. None
  41. None
  42. None
  43. None
  44. None
  45. None
  46. None
  47. None
  48. None
  49. Google Performance Tips • Avoid landing page redirects • Avoid

    plugins • Configure the viewport • Enable compression • Improve server response $me • Inline CSS • Leverage browser caching
  50. Google Performance Tips • Minify resources • Op$mize images •

    Op$mize CSS delivery • Priori$ze visible content • Remove render-blocking JavaScript • Size content to viewport • Size tap targets appropriately • Use asynchronous scripts • Use legible font sizes
  51. None
  52. None
  53. None
  54. None
  55. npm install psi

  56. psi dus$nwhi*le.com

  57. None
  58. None
  59. None
  60. Google on Browser Performance • Eliminate render-blocking JavaScript and CSS

    • To deliver the fastest $me to first render, you want to minimize and (where possible) eliminate the number of cri$cal resources on the page, minimize the number of downloaded cri$cal bytes, and op$mize the cri$cal path length. • Op$mize JavaScript Use • JavaScript resources are parser blocking by default unless marked as async or added via a special JavaScript snippet. Parser blocking JavaScript forces the browser to wait for the CSSOM and pauses construc$on of the DOM, which in turn can significantly delay the $me to first render. • Prefer async JavaScript resources • Async resources unblock the document parser and allow the browser to avoid blocking on CSSOM prior to execu$ng the script. Olen, if the script can be made async, it also means it is not essen$al for the first render - consider loading async scripts aler the ini$al render. • Avoid synchronous server calls • Use the navigator.sendBeacon() method to limit data sent by XMLH*pRequests in unload handlers. Because many browsers require such requests to be synchronous, they can slow page transi$ons, some$mes no$ceably. The following code shows how to use navigator.sendBeacon() to send data to the server in the pagehide handler instead of in the unload handler. • Defer parsing JavaScript • Any non-essen$al scripts that are not cri$cal to construc$ng the visible content for the ini$al render should be deferred to minimize the amount of work the browser has to perform to render the page.
  61. Google on Browser Performance • Avoid long running JavaScript •

    Long running JavaScript blocks the browser from construc$ng the DOM, CSS OM, and rendering the page. As a result, any ini$aliza$on logic and func$onality that is non-essen$al for the first render should be deferred un$l later. If a long ini$aliza$on sequence needs to be run, consider splijng it into several stages to allow the browser to process other events in between. • Op$mize CSS Use • CSS is required to construct the render tree and JavaScript will olen block on CSS during ini$al construc$on of the page. You should ensure that any non- essen$al CSS is marked as non-cri$cal (e.g. print and other media queries), and that the amount of cri$cal CSS and the $me to deliver it is as small as possible. • Put CSS in the document head • All CSS resources should be specified as early as possible within the HTML document such that the browser can discover the <link> tags and dispatch the request for the CSS as soon as possible. • Avoid CSS imports • CSS import (@import) direc$ve enables one stylesheet to import rules from another stylesheet file. However, these direc$ves should be avoided because they introduce addi$onal roundtrips into the cri$cal path: the imported CSS resources are discovered only aler the CSS stylesheet with the @import rule itself has been received and parsed. • Inline render-blocking CSS • For best performance, you may want to consider inlining the cri$cal CSS directly into the HTML document. This eliminates addi$onal roundtrips in the cri$cal path and if done correctly can be used to deliver a “one roundtrip” cri$cal path length where only the HTML is a blocking resource.
  62. Browser Performance Best Prac$ces • Compressing your JavaScript with Closure

    Compiler • CSS: Using every declara$on just once • Op$mizing JavaScript code • Prefetching resources • Minimizing browser reflow
  63. None
  64. None
  65. Op$mizing Content Efficiency • Elimina$ng unnecessary downloads • Op$mizing encoding

    and transfer size of text-based assets • Prefetch resources based on user ac$ons • Image op$miza$on • Web font op$miza$on • HTTP caching
  66. CSS Performance • Avoid universal rules • Don’t qualify ID

    rules with tag names or classes • Use the most specific category possible • Avoid the descendant selector • Ques$on all usages of the child selector • Rely on inheritance • Avoid vendor-specific features unless necessary • Remove unused css (uncss)
  67. Efficiency of CSS selectors • id (#myid) • class (.myclass)

    • tag (div, h1, p) • adjacent sibling (h1 + p) • child (ul > li) • descendent (li a) • universal (*) • a*ribute (a[rel="external"]) • pseudo-class and pseudo element (a:hover, li:first)
  68. Steve Souders examined the performance impact of CSS selectors and

    determined that the delta between the best case and the worst case was 50ms. Don’t waste too much $me on it.
  69. Image Op$miza$on • Prefer vector formats: vector images are resolu$on

    and scale independent, which makes them a perfect fit for the mul$- device and high-resolu$on world. • Minify and compress SVG assets: XML markup produced by most drawing applica$ons olen contains unnecessary metadata which can be removed; ensure that your servers are configured to apply GZIP compression for SVG assets. • Pick best raster image format: determine your func$onal requirements and select the one that suits each par$cular asset. • Experiment with op$mal quality sejngs for raster formats: don’t be afraid to dial down the “quality” sejngs, the results are olen very good and byte savings are significant. • Remove unnecessary image metadata: many raster images contain unnecessary metadata about the asset: geo informa$on, camera informa$on, and so on. Use appropriate tools to strip this data. • Serve scaled images: resize images on the server and ensure that the “display” size is as close as possible to the “natural” size of the image. Pay close to a*en$on to large images in par$cular, as they account for largest overhead when resized! • Automate, automate, automate: invest into automated tools and infrastructure that will ensure that all of your image assets are always op$mized.
  70. None
  71. None
  72. Web Font Performance • There are four primary levers that

    determine the performance impact of web fonts on the page: • The total number of fonts and font-weights used on the page. • The total byte size of fonts used on the page. • The transfer latency of the font resource. • The $me when the font downloads are ini$ated.
  73. Web Font Op$miza$on • Audit and monitor your font use:

    do not use too many fonts on your pages, and for each font, minimize the number of used variants. This will assist in delivering a more consistent and a faster experience for your users. • Subset your font resources: many fonts can be subset, or split into mul$ple unicode-ranges to deliver just the glyphs required by a par$cular page - this reduces the filesize and improves download speed of the resource. However, when defining the subsets be careful to op$mize for font re-use - e.g. you don’t want to download a different but overlapping set of characters on each page. A good prac$ce is to subset based on script - e.g. La$n, Cyrillic, and so on. • Deliver op$mized font formats to each browser: each font should be provided in WOFF2, WOFF, EOT, and TTF formats. Make sure to apply GZIP compression to EOT and TTF formats, as they are not compressed by default. • Specify revalida$on and op$mal caching policies: fonts are sta$c resources that are infrequently updated. Make sure that your servers provide a long-lived max-age $mestamp, and a revalida$on token, to allow for efficient font re-use between different pages. • Use Font Loading API to op$mize the Cri$cal Rendering Path: default lazyloading behavior may result in delayed text rendering. Font Loading API allows us to override this behavior for par$cular fonts, and to specify custom rendering and $meout strategies for different content on the page. For older browsers that do not support the API, you can use the webfontloader JavaScript library or use the CSS inlining strategy.
  74. None
  75. Caching Op$miza$on • Use consistent URLs: if you serve the

    same content on different URLs, then that content will be fetched and stored mul$ple $mes. Tip: note that URLs are case sensi$ve! • Ensure the server provides a valida$on token (ETag): valida$on tokens eliminate the need to transfer the same bytes when a resource has not changed on the server. • Iden$fy which resources can be cached by intermediaries: those with responses that are iden$cal for all users are great candidates to be cached by a CDN and other intermediaries. • Determine the op$mal cache life$me for each resource: different resources may have different freshness requirements. Audit and determine the appropriate max-age for each one. • Determine the best cache hierarchy for your site: the combina$on of resource URLs with content fingerprints, and short or no-cache life$mes for HTML documents allows you to control how quickly updates are picked up by the client. • Minimize churn: some resources are updated more frequently than others. If there is a par$cular part of resource (e.g. JavaScript func$on, or set of CSS styles) that are olen updated, consider delivering that code as a separate file. Doing so allows the remainder of the content (e.g. library code that does not change very olen), to be fetched from cache and minimizes the amount of downloaded content whenever an update is fetched.
  76. Op$mize Cri$cal Rendering Path • Analyze and characterize your cri$cal

    path: number of resources, bytes, length. • Minimize number of cri$cal resources: eliminate them, defer their download, mark them as async, etc. • Op$mize the order in which the remaining cri$cal resources are loaded: you want to download all cri$cal assets as early as possible to shorten the cri$cal path length. • Op$mize the number of cri$cal bytes to reduce the download $me (number of roundtrips).
  77. None
  78. None
  79. None
  80. None
  81. None
  82. npm install sitespeed.io

  83. sitespeed.io -u dus$nwhi*le.com

  84. None
  85. None
  86. None
  87. None
  88. None
  89. None
  90. None
  91. None
  92. None
  93. None
  94. None
  95. Automate your frontend workflows

  96. None
  97. None
  98. None
  99. npm install -g grunt-cli

  100. None
  101. None
  102. npm install -g gulp

  103. None
  104. Grunt and Gulp make it easy to incorporate best prac0ces

    and automate the tedious parts of web development.
  105. None
  106. None
  107. npm install -g bower

  108. None
  109. npm install -g yo

  110. None
  111. Use Bower (for dependencies), Grunt/Gulp (for automa$on), and Yeoman (for

    bootstrapping)
  112. npm install -g yo bower gulp

  113. None
  114. npm install -g generator-gulp-webapp

  115. mkdir webapp

  116. yo gulp-webapp

  117. None
  118. npm install

  119. bower install

  120. gulp

  121. gulp serve

  122. gulp test

  123. gulp serve:dist

  124. None
  125. A live refactoring for performance

  126. None
  127. None
  128. ngrok h*p 3000

  129. None
  130. None
  131. None
  132. None
  133. None
  134. None
  135. None
  136. None
  137. None
  138. None
  139. None
  140. None
  141. TodoMVC has been called many things including the 'Speed-da$ng' and

    'Rose*a Stone' of MV* frameworks.
  142. git clone h*ps://github.com/tastejs/todomvc

  143. npm install

  144. bower install

  145. gulp

  146. gulp serve

  147. None
  148. Google Web Starter Kit

  149. None
  150. None
  151. None
  152. None
  153. git clone h*ps://github.com/google/web-starter-kit.git

  154. npm install

  155. bower install

  156. gulp

  157. gulp serve

  158. None
  159. None
  160. Automated Performance Improvements

  161. None
  162. None
  163. None
  164. None
  165. None
  166. None
  167. Monitor performance on the server-side and client-side

  168. None
  169. Monitor your end user latency with Episodes.js or Google Analy$cs

    SiteSpeed
  170. None
  171. None
  172. None
  173. None
  174. Monitor the end user experience with applica$on performance management tools

    (that use naviga$on + resource $ming apis)
  175. None
  176. None
  177. None
  178. None
  179. None
  180. None
  181. Understanding the impact of HTTP2 • Todays best prac0ces are

    tomorrows an0-pa6erns • The limita$ons of HTTP/1.X forced us to develop various applica$on workarounds (sharding, concatena$on, spri$ng, inlining, etc.) to op$mize performance. However, in the process we’ve also introduced numerous regressions: poor caching, unnecessary downloads, delayed execu$on, and more. • HTTP/2 eliminates the need for these hacks and allows us to both simplify our applica$ons and deliver improved performance. • You should unshard (domains), unconcat (css/javascript), and unsprite your assets (images) • You should switch from inlining to server push • Read Ilya Grigorik awesome book on browser performance - h*p://hpbn.co/h*p2
  182. Recap / Take aways § Treat performance as a feature

    § Implement caching and queuing to improve server-side latency § Start with a solid founda0on by leveraging yeoman or google web starter kit § Leverage nginx/apache boilerplate server configs for sane web server secngs § Follow best prac0ces to op0mize delivery of javascript, css, images, and fonts § Op0mize for cri0cal rendering path § Google Chrome Developer Tools is your friend for profiling § Automate build and deployment best prac0ces with Gulp/Grunt § Use PageSpeed Insights, SiteSpeed.io, WebPageTest.org as part of development lifecycle § If you can’t improve the code then leverage mod_pagespeed, Yo6a, or CloudFlare § Monitor the real user experience with applica0on performance management tools
  183. Resources

  184. https://developers.google.com/web/fundamentals

  185. https://developers.google.com/web/tools/starter-kit/

  186. http://yeoman.io/blog/performance-optimization.html

  187. https://speakerdeck.com/addyosmani/automating-front-end-workflow

  188. h6p://hpbn.co/h6p2

  189. None
  190. None
  191. Recommended Velocity Sessions § Building High Performance Progressive Web Apps

    - Aditya Punjabi § High Performance Browser Networking - Ilya Grigorik § Scaling Front-End Performance - Patrick Meehan § Experiences of HTTP/2 in the real world - Michael Gooding § Outages, ownership, and cralsmanship: A devops story - Adam Cath
  192. Most of this content comes directly from: Google Web Fundamentals

    Google PageSpeed Rules Ryan Tomayko’s “Things Caches Do” Addy Osmani’s “Automa$ng Workflow” Ilya Grigorik “High Performance Browser Networking”
  193. Find these slides on SpeakerDeck h6ps://speakerdeck.com/

  194. Ques0ons?

  195. None