Skip to content

Optimizing HTML, CSS and JS delivery

Dmitri Skjorshammer edited this page Mar 10, 2015 · 3 revisions

When the browser receives an HTML from the server, it starts parsing it into a Document Object Model. If any style tags (CSS) are detected, it will block the DOM constructor, and begin constructing CSSOM - CSS Object Model [1].

The DOM and CSSOM are combined into a render tree, and then a “Layout” step is run to compute geometry of each element. Finally, the “Paint” step is running to paint the nodes [2]

As a result of DOM and CSSOM creating the render tree, the CSS is a render-blocking resource. The goal is therefore to get it down to the client as soon as possible. There are a few things you should do:

Inline relatively small CSS. Larger CSS should be kept in a separate file so it can be cached by the browser [3] Use media queries (print, screen) to avoid loading CSS that don’t fit the media [4] DO NOT add CSS into your HTML (great performance hit) Inline CSS for above the fold content (those that the browser sees when it loads the page). All below-the-fold content will be loaded via a JavaScript snippet [5]

JavaScript is also a render-blocking resource. When the HTML parser encounters a "script" tag, it stop DOM rendering and CSSOM rendering, and starts the JavaScript engine. How do we prevent this? We can specify "script" tags with a “async” tag to tell HTML parser to continue parsing without stopping. [6]

Knowing this, always try to optimize these 3 steps:

  • Critical Resource: resource that may block initial rendering of the page.
  • Critical Path Length: number of roundtrips, or the total time required to fetch all of the critical resources.
  • Critical Bytes: total amount of bytes required to get to first render of the page, which is the sum of the transfer filesizes of all critical resources. Our first example with a single HTML page contained a single critical resource (the HTML document), the critical path length was also equal to 1 network roundtrip (assuming file is small), and the total critical bytes was just the transfer size of the HTML document itself.

References

  1. https://developers.google.com/web/fundamentals/performance/critical-rendering-path/constructing-the-object-model?hl=en
  2. https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-tree-construction?hl=en
  3. https://developers.google.com/speed/pagespeed/module/filter-css-inline
  4. https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-blocking-css?hl=en
  5. http://www.feedthebot.com/pagespeed/optimize-css-delivery.html
  6. https://developers.google.com/web/fundamentals/performance/critical-rendering-path/adding-interactivity-with-javascript?hl=en
Clone this wiki locally