Combine Heads

Configuration

The 'Combine Heads' filter is enabled by specifying:

Apache:
ModPagespeedEnableFilters combine_heads
Nginx:
pagespeed EnableFilters combine_heads;

in the configuration file.

Description

'Combine Heads' combines multiple heads into one. Technically HTML documents are not allowed to have multiple <head> sections, but sites which aggregate content from multiple sources sometimes have them. This filter moves the content from later <head> sections into the first head. This filter can change the order of content (e.g. CSS and JS) in the later <head> sections relative to intervening <body> elements.

Operation

The 'Combine Heads' filter operates by moving the content of all <head> sections into the first <head> section.

For example, if the HTML document looks like this:

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="styles/yellow.css">
    <link rel="stylesheet" type="text/css" href="styles/blue.css">
  </head>
  <body>
    <div class="blue yellow big bold">
      Hello, world!
    </div>
  </body>
  <head>
    <link rel="stylesheet" type="text/css" href="styles/big.css">
    <link rel="stylesheet" type="text/css" href="styles/bold.css">
  </head>
</html>

Then PageSpeed will rewrite it into:

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="styles/yellow.css">
    <link rel="stylesheet" type="text/css" href="styles/blue.css">
    <link rel="stylesheet" type="text/css" href="styles/big.css">
    <link rel="stylesheet" type="text/css" href="styles/bold.css">
  </head>
  <body>
    <div class="blue yellow big bold">
      Hello, world!
    </div>
  </body>
</html>

Example

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

Limitations

The 'Combine Heads' filter operates within the scope of a "flush window". Specifically, large or dynamically generated HTML files my be "flushed" by the resource generator before they are complete. If the CSS combiner encounters a Flush prior to the end of the first <head>, then subsequent <head>s will not be merged in.

Note

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

Risks

This filter is considered medium-risk. If there are style or script tags in the body, between two heads, then this rewrite pass can change their order. The risk is reduced if the move_css_to_head filter is also enabled. Additionally, JavaScript that is executed before a later <head> will see a different view of the DOM in the presence of this rewriter. If there is such JavaScript embedded in the middle of a page then this rewriter may change its behavior.