Move CSS to Head

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

Objective

Optimize browser rendering by allowing all of the CSS to be specified in the head section.

PageSpeed rule

This rewriter implements the PageSpeed rule for optimizing browser rendering.

Description

This rewriter reduces the number of times a browser must re-flow the document by ensuring that all CSS styles (inline and outlined) are parsed in the document head section, before any body elements are introduced. All <style> and <link> tags, within the head and body sections, are moved to the head section, in such a way that their relative ordering is preserved.

Operation

This rewriter parses the HTML document, finds all <style> and <link> tags and moves these tags to the end of the head section.

Example

The example below shows the HTML before rewriting:

<html>
  <head>
  </head>
  <body>
    <style type="text/css"> .big { font-size: 8em; } </style>
    <div class="big">
      Hello, world!
    </div>
  </body>
</html>

and after rewriting:

<html>
  <head>
    <style type="text/css"> .big { font-size: 8em; } </style>
  </head>
  <body>
    <div class="big">
      Hello, world!
    </div>
  </body>
</html>

Limitations

PSS streams HTML to users, and thus will only see some HTML content after other content has already been sent to users. If PSS has already sent the <head> section to the user, subsequently discovered CSS elements will not be moved to <head>.