Prioritize Critical CSS

PageSpeed Service was turned off on August 3rd, 2015. Please see Turndown Information for PageSpeed Service.

Objective

This rewriter improves page render times by identifying CSS rules needed to render the page, inlining those critical rules and deferring the load of the full CSS resources.

Description

Prioritize Critical CSS parses the CSS and replaces it with inlined CSS that contains only the rules used on the page. This avoids any blocking CSS requests needed for the initial render. It also collects all CSS tags and appends them to the HTML in the same order they were found. This will make all style rules available after page load.

Deferring style rules that are not used by the document delays downloading unnecessary bytes and allows the browser to start rendering sooner per this best practice.

Example

For example, if the HTML document looks like this:

<html>
  <head>
    <link rel="stylesheet" href="small.css">
  </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>

And the resource small.css is like this:

  .yellow {background-color: yellow;}
  .blue {color: blue;}
  .big { font-size: 8em; }
  .bold { font-weight: bold; }

Then PageSpeed Service will rewrite it into:

<html>
  <head>
    <style>
      .blue{color:blue;}
    </style>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>
<noscript><link rel="stylesheet" href="small.css"></noscript>

The original small.css is loaded after onload of the page. The application order of CSS rules is maintained by injecting all the <style> and <link> elements into the document through JavaScript.

The effect of this rewriter can be observed on pssdemos.com before and after rewriting. You will need to reload the page a few times to see the effect, since this rewriter computes the critical rules for the page based on previous page renders.

Requirements

Prioritize Critical CSS computes critical CSS only if the corresponding CSS file is "public" cacheable.

Risks

Prioritize Critical CSS filter is moderate risk. It should be safe for most pages, but it could potentially cause reflow of the page. If different content (with substantially different styles) is served for the same URL based on cookies, IP, user agent, etc., then this filter could potentially show unstyled content before it loads the page completely, or in certain cases it could break rendering completely.

Prioritize Critical CSS filter adds inlined CSS to the HTML, increasing its size. The overhead of the extra inlined CSS can outweigh the benefit if the CSS resources are already in the browser's cache. However it will still benefit from faster processing of the CSS in the browser.

Limitations

This rewriter cannot compute critical CSS for CSS files under IE conditional comments and is disabled if it detects an IE user agent.