O slideshow foi denunciado.
Seu SlideShare está sendo baixado. ×

Building high performing web pages

Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Carregando em…3
×

Confira estes a seguir

1 de 34 Anúncio

Mais Conteúdo rRelacionado

Diapositivos para si (20)

Quem viu também gostou (19)

Anúncio

Semelhante a Building high performing web pages (20)

Mais recentes (20)

Anúncio

Building high performing web pages

  1. 1. + High Performing web pages Nilesh Bafna
  2. 2. + How does the web browser renders a web page?  Constructing the Object models  Render tree construction  Layout stage  Paint  Composite © Perennial Systems Inc 2
  3. 3. + Constructing Object model Bytes -> Characters -> Tokens -> Nodes -> Object Model © Perennial Systems Inc 3
  4. 4. + Render tree Render Tree Creation 1) Start at the root node of the DOM 2) Nodes which are not visible are omitted like script, meta etc 3) Additional nodes which are hidden by CSS are also omitted from the final render tree 4) Each visible node and its CSS rules are merged in a node © Perennial Systems Inc 4
  5. 5. + Layout stage  This stage involves the calculation of the exact position and size of every node within the viewport  It starts with the top parent and the output is a box model with exact absolute pixel positions updated in the render tree. <html> <head> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>Critial Path: Hello world!</title> </head> <body> <div style="width: 50%"> <div style="width: 50%">Hello world!</div> </div> </body> </html> © Perennial Systems Inc 5
  6. 6. + Paint & Composite  Once the layout is complete the browser issues a Paint setup and Paint event for converting the render tree to pixels on screen  Time required to paint varies on the number of nodes and complexity of the styles. Eg: Solid colors take less time to paint, drop shadows take more time.  The drawing happens on different surfaces called layers  Process of ordering the layers while painting so that they are seen in the right order on the screen is called Composite. © Perennial Systems Inc 6
  7. 7. + How does browser react to scripts and styles within code?  While parsing the page, if the browser comes across a script, it has to stop the creation of the DOM and pass the control to Javascript engine to execute the script.  Javascript cannot be executed if any style sheets on the page are still to be loaded and CSS object model is pending to be formed. Hence, now the parsing stops till both the CSSOM is created and then the script is executed. Now consider, these scripts and stylesheets to be external. Nightmare??  Preload scanner: Browsers are smart to optimize when the parsing is halted by the above operations. It runs a preload scanner for the further HTML only to identify if there are any any other resources to be fetched. The preload scanner initiates them meanwhile. Note: The preload scanner does not modify the DOM at all, it simply cannot. © Perennial Systems Inc 7
  8. 8. + Minimize Critical rendering path  Number of critical resources: Number of resources that may block the critical rendering path  Size of the critical resources: Total bytes to get the first render of the page  Minimum critical path length: number of round trips. The number of round trips will depend on the length of the file. © Perennial Systems Inc 8
  9. 9. + Important events during the critical rendering path  domLoading: the browser is about to start parsing the first received byte of HTML  domInteractive: All HTML parsing is complete and DOM Object Model is created.  domContentLoaded: This is fired when both DOM and CSS trees are created. All parser blocking Javascript have finished execution. Render tree can now be created.  domComplete: The event is fired when the page and its sub-resources are downloaded and ready. © Perennial Systems Inc 9
  10. 10. + Let’s understand this better… <html> <head> <meta name=“viewport" content="width=device-width,initial-scale=1”> <link href=”my_style.css" rel="stylesheet"> <title>Example 1</title> </head> <body> <p> Example 1 </p> </body> <script src=”my_app.js"></script> </html> Number of critical resources: 3 Size of critical resources: Total bytes of HTML + CSS + Javascript Minimum critical path length: 2 or more depending on size © Perennial Systems Inc 10
  11. 11. + How to speed up page performance  Render blocking resources  CSS  Javascript & Optimization  Optimized Images  Very Low TTFB  Prioritize content delivery  Configure the viewport  Enable Compression  Leverage browser Caching  Minified resources  Use Keep-Alive  Web fonts  Use CDN  Reduce the number of repaint and reflows © Perennial Systems Inc 11
  12. 12. + Render blocking CSS  Media queries and Media types allow us to mark some CSS resources as non render blocking.  The browser does not wait for non render blocking CSS and is used to optimize the time to first render for a page.  All CSS resources with render blocking or non blocking will be downloaded by the browser. Eg: <link href="style.css" rel="stylesheet"> <link href="style.css" rel="stylesheet" media="all"> <link href="portrait.css" rel="stylesheet" media="orientation:portrait"> <link href="print.css" rel="stylesheet" media="print"> © Perennial Systems Inc 12
  13. 13. + Render blocking CSS  If external CSS resources are small, it is a good idea to embed it within the HTML page under the style tag.  Reduce the complexity of the style calculations. Measure the style recalculation cost and optimize by ensuring only required elements are styled. How to measure will be covered in a different presentation.  Avoid CSS @import  Combine CSS in one file during production deployment  Don't inline CSS attributes with the HTML  Programmatically loadCSS which is not applicable to first prioritized HTML content.  To identify important CSS use tools like Critical tool. Above the fold CSS. © Perennial Systems Inc 13
  14. 14. + Parser blocking Javascript  When a Javascript code is reached, the browser blocks the execution of the DOM and hands over the control to Javascript engine till the script is executed completely and resumes the reconstruction of DOM at the same point.  The browser delays the execution of Javascript till the CSS object model is created  The location of the script tag within the document is very important <script src=“myscript.js” async></script> Tells the browser it does not need to wait for the execution and can start once the file is fetched from the server. This unblocks the DOM creation. Placement order of the style and script tag play a very important role for managing this experience. © Perennial Systems Inc 14
  15. 15. + Optimizing Javascript  Inline JS when necessary reducing network round trip.  Combine the Javascript file to reduce network calls.  requestAnimationFrame instead of setTimeout  Web workers for intensive operations (Do not have access to DOM)  JS profiler to identify slow Javascript inside Chrome dev tools  Defer loading javascript. Use of defer keyword may not work across browsers. Programmatic loading of JS after page load can be used to download and add javascript not affecting critical above the fold content.  Use async version of popular 3rd party scripts. Eg: facebook, Google analytics, twitter etc.. © Perennial Systems Inc 15
  16. 16. + Optimizing Javascript  Avoid forced synchronous layouts  Avoid layout thrashing  Read and write cycles  Avoid long running input handlers and style changes in them (onMouseDown, onChange etc..) function logBoxHeight() { box.classList.add(’myCSS'); // Gets the height of the box in pixels // and logs it out. console.log(box.offsetHeight); } function resizeAllParagraphsToMatchBlockWidth() { // Puts the browser into a read-write-read-write cycle. for (var i = 0; i < paragraphs.length; i++) { paragraphs[i].style.width = box.offsetWidth + 'px'; } } FastDOM, a library to reorder the reading and writing and making it async © Perennial Systems Inc 16
  17. 17. +  Prefer vector formats: vector images are resolution and scale independent, which makes them a perfect fit for the multi-device and high- resolution world.  Minify and compress SVG assets: XML markup produced by most drawing applications often contains unnecessary metadata which can be removed; ensure that your servers are configured to apply GZIP compression for SVG assets.  Remove unnecessary image metadata: many raster images contain unnecessary metadata about the asset: geo information, camera information, and so on. Use appropriate tools to strip this data.  WebP is a very promising format, though not supported across all platforms; they should be used in native applications and its webviews. Optimized Images © Perennial Systems Inc 17
  18. 18. + Optimized Images  Use base64 for very small images < 5kb to avoid additional calls. Google is not able to index base64 images which can be addressed by the meta tag. <meta property="og:image" content=images/myimage.png>  Images should be optimized with Lossy filter (eliminates pixel data) -> Lossless filter (Compression) pipeline.  Choosing appropriate image format:  Animated images-> Use GIF  High quality lossless images-> PNG  Medium-low quality -> JPEG (experiment with quality based on use case)  Deliver large image assets size as close to the display size as possible. © Perennial Systems Inc 18
  19. 19. + Very Low Time to first byte (TTFB) Reasons for high TTFB: 1) Dynamic web page creation: This can be addressed by deploying web page caching for dynamic pages. 2) Web server configuration: .htaccess offers convenience but can be huge performance issues specially on apache. It can be anything from database performance, slow application logic, slow routing, slow framework/libraries, resource starvation (CPU, Memory, Disk). Less than 100 milliseconds is superb 200 milliseconds is ideal Anything else is bad... © Perennial Systems Inc 19
  20. 20. + Prioritize content delivery  Above the fold is a portion of the web page that is visible in web browser. Always load the critical portion first and defer loading the rest of the page.  The CSS delivery can be split into 2 parts to ensure faster page render.  Prioritize loading of most important information first and deferring the rest using lazy loading. © Perennial Systems Inc 20
  21. 21. + Configure the Viewport  <meta name=viewport content="width=device-width, initial- scale=1">  Avoid minimum-scale, maximum-scale, user-scalable. These options negatively impact accessibility and should generally be avoided.  If necessary use different styling for small and large screens using appropriate media queries. © Perennial Systems Inc 21
  22. 22. + Enable Compression  Enabling Gzip compressions as all browsers today understand Gzip compression.  Compression is enabled via webserver configuration  Compression of all HTTP requests results in compression of as high as 50- 75% in terms of bandwidth and page load time. © Perennial Systems Inc 22
  23. 23. + Leverage browser caching  Network calls are the most expensive operations.  It is highly recommended an appropriate caching strategy is adopted for every external resource. Eg: whether the resource can be cached and by whom, for how long, and if applicable, how it can be efficiently revalidated when the caching policy expires.  Cache-Control defines how, and for how long the individual response can be cached by the browser and other intermediate caches  ETag provides a revalidation token that is automatically sent by the browser to check if the resource has changed since the last time it was requested. © Perennial Systems Inc 23
  24. 24. + Minified resources  All the HTML, CSS and JS can be minified typically using a build process to deploy minified resources on the production environment.  To minify HTML, try HTMLMinifier  To minify CSS, try CSSNano and csso.  To minify JavaScript, try UglifyJS. © Perennial Systems Inc 24
  25. 25. + Use keep-alive  This method allows the browser to use the same connection for different HTTP requests. This is useful since a web page involves multiple files like CSS, Images, JS and HTML  This avoids creating a new connection for every file request.  Keep-Alive is to be configured on the web server.  Specially useful in shared environments where keep-alive is generally turned off. © Perennial Systems Inc 25
  26. 26. + Web fonts  4 types of fonts available for web: WOFF 2, WOFF, TTF, EOT.  The support for each of them is limited with WOFF being the mostly widely supported and WOFF 2 is still work in progress.  EOT and TTF are not compressed by default. Ensure server side compression while delivery of these fonts.  WOFF has built in compression ensure optimal compression settings. WOFF2 gives 30% reduction in file size.  Separate files for different styles like itlatic, normal. The browser uses the one it needs Use format hint so that the browser checks and downloads the format it supports. @font-face { font-family: 'Awesome Font'; font-style: normal; font-weight: 400; src: local('Awesome Font'), url('/fonts/awesome.woff2') format('woff2'), url('/fonts/awesome.woff') format('woff'), url('/fonts/awesome.ttf') format('ttf'), url('/fonts/awesome.eot') format('eot'); } url() directive allows us to load external fonts, and are allowed to contain an optional format() hint indicating the format of the font referenced by the provided URL. © Perennial Systems Inc 26
  27. 27. + Web fonts  Unicode range setting: unicode-range: U+000-5FF; under @font-face  Manual subsetting Use the open-source pyftsubset to subset and optimize fonts. Some font services allow manual subsetting via custom query parameters to manually get a font subset.  The browser downloads the required font after creating the render tree. This causes the web page rendering to be delayed till the font is not available. Devs can use the font loading API to micro manage this font loading process to get the required fonts before the render tree. (Browser dependent)  The devs can inline the font in the CSS to force the browser to download the font while creating the CSSOM. We should keep a separate CSS file for fonts with large max age so that the fonts are not downloaded every time a newer version of CSS is built and deployed. (Be very careful)  Use HTTP Caching for the fonts. © Perennial Systems Inc 27
  28. 28. + Use CDN  Content delivery network is a network of servers placed in different geographic locations with your website content and delivered to the clients from the closest location for reduced network latency.  CDN can be used for delivery of all static resources: CSS, JS, Images, HTML  Popular CNDs  Cloudflare (has free option)  Fastly  Amazon CloudFront  MaxCDN  Akamai  Cachefly  Keycdn © Perennial Systems Inc 28
  29. 29. + Repaint and Reflows  When part or whole of the render tree needs to be revalidated and the node dimensions recalculated is called “Reflow”.  When part of the screen needs to be updated due to changes in style it requires the browser to paint that area of the screen. This is called Repaint.  Code that causes reflow or repaint  Adding, removing, updating DOM nodes  Hiding a DOM node with display: none (reflow and repaint) or visibility: hidden (repaint only)  Moving, animating a DOM node on the page (repaint)  Adding a stylesheet, tweaking style properties (reflow or repaint or both)  User action such as resizing the window, changing the font size, or browser scrolling © Perennial Systems Inc 29
  30. 30. + Expensive operations  Browsers optimizes the reflows and repaint operations by performing in batches. Though are certain functions that causes the browser to perform the reflow and/or repaints immediately and hence should be used very carefully. Element: clientHeight, clientLeft, clientTop, clientWidth, focus(), getBoundingClientRect(), getClientRects(), innerText, offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerText, scrollByLines(), scrollByPages(), scrollHeight, scrollIntoView(), scrollIntoViewIfNeeded(), scrollLeft, scrollTop, scrollWidth Frame, Image: height, width Range: getBoundingClientRect(), getClientRects() SVGLocatable: computeCTM(), getBBox() SVGTextContent: getCharNumAtPosition(), getComputedTextLength(), getEndPositionOfChar(), getExtentOfChar(), getNumberOfChars(), getRotationOfChar(), getStartPositionOfChar(), getSubStringLength(), selectSubString() SVGUse: instanceRoot Window: getComputedStyle(), scrollBy(), scrollTo(), scrollX, scrollY, webkitConvertPointFromNodeToPage(), webkitConvertPointFromPageToNode() © Perennial Systems Inc 30
  31. 31. + Recommendations for minimizing Repaint and Reflow  Don’t read and write to style sheet very quickly. Batch the query state and change state statements  Don’t change individual style one by one if there are multiple changes, use cssText property as it batches the application of change  Don’t ask for computed style multiple times. Store in local variable and reuse them specially for expensive operations. © Perennial Systems Inc 31
  32. 32. + PageSpeed module – Apache, Nginx  Page speed module is developed by Google and can be configured with Apache or Nginx to perform web page optimization best practices.  These optimizations are performed by configuring filters in the page speed module.  Categories of filters:  Optimize Caching  Minimize round trip times  Minimize request overhead  Minimize payload size  Optimize Browser rendering © Perennial Systems Inc 32
  33. 33. + What’s next?  How to measure page performance using tools?  JavaScript Internals © Perennial Systems Inc 33
  34. 34. + References  https://developers.google.com/web/fundamentals/performance/?hl=en  https://developers.google.com/speed/docs/insights/about  https://jonsuh.com/blog/need-for-speed-2/  https://classroom.udacity.com/courses/ud884/  http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/  http://gent.ilcore.com/2011/05/how-web-page-loads.html  http://gent.ilcore.com/2011/03/how-not-to-trigger-layout-in-webkit.html © Perennial Systems Inc 34

×