Move CSS to Head

Configuration

The 'Move CSS to head' filter is enabled by specifying:

Apache:
ModPagespeedEnableFilters move_css_to_head
Nginx:
pagespeed EnableFilters move_css_to_head;

in the configuration file.

Description

'Move CSS to head' seeks to reduce the number of times the browser must re-flow the document by ensuring that the CSS styles are all parsed in the head, before any body elements are introduced.

This is based on the best practice for optimizing browser rendering.

Operation

The 'Move CSS to head' filter operates only on CSS <link and <style> tags found after the </head> and moves these links back into the <head> ... </head> section.

For example, if the HTML document looks like this:

<html>
  <head>
  </head>
  <body>
    <script src="script.js" type="text/javascript"></script>
    <div class="blue yellow big bold">
      Hello, world!
    </div>
    <style type="text/css">
      .foo { color: red; }
    </style>
    <link rel="stylesheet" type="text/css" href="styles/all_styles.css">
  </body>
</html>

Then PageSpeed will rewrite it into:

<html>
  <head>
    <style type="text/css">
      .foo { color: red; }
    </style>
    <link rel="stylesheet" type="text/css" href="styles/all_styles.css">
  </head>
  <body>
    <script src="script.js" type="text/javascript"></script>
    <div class="blue yellow big bold">
      Hello, world!
    </div>
  </body>
</html>

In some browsers, the original version will flash quickly as the browser will render the "Hello, world!" text before it sees the style tags providing definitions for the CSS classes. This transformation will eliminate that flash, but the end result will be the same.

Example

You can see the filter in action at www.modpagespeed.com on this example.

Limitations

This filter operates within the scope of a "flush window". Specifically, large, or dynamically generated HTML files may be "flushed" by the resource generator before they are complete. If the filter encounters a flush after the end of the <head> section, subsequently encountered CSS elements will not be moved into the <head> section.

Risks

This filter is considered low risk. However, JavaScript that is executed before a CSS element will see a different view of the DOM in the presence of this rewriter: the CSS element will now be in the head. If there is such JavaScript embedded in the middle of a page then this rewriter may change its behavior.