Automate Critical Above The Fold Css Authoring And Embedding

March 19, 2015


We all know the best way to serve our website to our audience is to serve it fast, as fast as humanly possible. A couple of key factors for speed are how you serve css and javascript in your page. One thing Google suggests to do is to inline in the head of your document the “above the fold” css, which translates to all the css that paint what users see first when accessing your website: the header, the menu, the main content… The footer is clearly not above-the-fold material for example. Talking about performance, when testing your page speed on Google’s PageSpeed Insights tool, you probably came across this warning at some point: abovethefold

Eliminate render-blocking JavaScript and CSS in above the fold content

There are many ways to do this and the one I prefer is using a grunt plugin called penthouse. Penthouse automatically extracts the above the fold css in a separate file, which you can later embed in the head of your documents either manually, or automatically.


Setting it up is pretty easy. Same old

npm install grunt-penthouse --save-dev

from the shell in the root of your project, enable it in your gruntfile with


and create a task like the following:

penthouse: {
    extract : {
        outfile : 'css/critical.css',
        css : 'css/main.css',
        url : 'http://localhost/your-website',
        width : 1200,
        height : 500

I automate the creation of this file everytime my css file changes. I use sass for css authoring, so my watch part of the gruntfile looks something like

css : {
  files : ['sass/**/*.scss'],
  tasks : ['sass', 'autoprefixer', 'penthouse'],
  options : {
    spawn : false,

You clearly see how this tasks chain work: sass compiles main.css main.css gets autoprefixed critical.css with the above the fold styles is produced.


What should we do with critical.css? Open it, copy the content and paste it in the head section of all of our pages? That’s tedious, no way this is maintainable. There’s a way to automate this if your project is made in php or any other language that can use includes. I use php so the way I automate this is hacking the file extension of the critical.css file into critical.css.php in the grunt task and then I include it in every page like this:

<style type="text/css">
  <?php include 'css/critical.css.php';?>

This way the embedding is automatic and always up-to-date and you won’t have to worry about anything. You can now safely move the main.css file at the bottom of the page. Team this up with deferring javascript and you’ll easily get ~10 points on the pagespeed score.

One bad thing about this approach is that, if you have linked images in the above the fold css, the paths won’t be updated and effective.

Share this:


Guest Posts

Recent Posts