title: Inlining critical CSS for first-time visits
url: https://adactio.com/journal/8504
hash_url: 70ce67ed910c56329a329c2ad194c75e

<p>After listening to <a href="http://www.filamentgroup.com/lab/performance-rwd.html">Scott rave on</a> about how much of a perceived-performance benefit he got from <a href="https://developers.google.com/speed/pagespeed/service/PrioritizeCriticalCss">inlining critical CSS</a> on first load, I thought I’d give it a shot over at <a href="https://thesession.org/">The Session</a>. On the chance that this might be useful for others, I figured I’d document what I did.</p>

<p>The idea here is that you can give a massive boost to the perceived performance of the first page load on a site by putting the most important CSS in the <code>head</code> of the page. Then you cache the full stylesheet. For subsequent visits you only ever use the external stylesheet. So if you’re squeamish at the thought of munging your CSS into your HTML (and that’s a perfectly reasonable reaction), don’t worry—this is a temporary workaround just for initial visits.</p>

<p>My particular technology stack here is using <a href="http://gruntjs.com/">Grunt</a>, Apache, and PHP with <a href="http://twig.sensiolabs.org/">Twig</a> templates. But I’m sure you can adapt this for other technology stacks: what’s important here isn’t the technology, it’s the thinking behind it. And anyway, the end user never sees <em>any</em> of those technologies: the end user gets HTML, CSS, and JavaScript. As long as that’s what you’re outputting, the specifics of the technology stack really don’t matter.</p>

<h3>Generating the critical CSS</h3>

<p>Okay. First question: how do you figure out which CSS is critical and which CSS can be deferred?</p>

<p>To help answer that, and automate the task of generating the critical CSS, Filament Group have made a Grunt task called <a href="https://github.com/filamentgroup/grunt-criticalcss">grunt-criticalcss</a>. I added that to my project and updated my Gruntfile accordingly:</p>

<pre><code>grunt.initConfig({
    // All my existing Grunt configuration goes here.
    criticalcss: {
        dist: {
            options: {
                url: 'http://thesession.dev',
                width: 1024,
                height: 800,
                filename: '/path/to/main.css',
                outputfile: '/path/to/critical.css'
            }
        }
    }
});
</code></pre>

<p>I’m giving it the name of my locally-hosted version of the site and some parameters to judge which CSS to prioritise. Those parameters are viewport width and height. Now, that’s not a perfect way of judging which CSS matters most, but it’ll do.</p>

<p>Then I add it to the list of Grunt tasks:</p>

<pre><code>// All my existing Grunt tasks go here.
grunt.loadNpmTasks('grunt-criticalcss');

grunt.registerTask('default', ['sass', etc., 'criticalcss']);
</code></pre>

<p>The end result is that I’ve got two CSS files: the full stylesheet (called something like <code>main.css</code>) and a stylesheet that only contains the critical styles (called <code>critical.css</code>).</p>

<h3>Cache-busting CSS</h3>

<p>Okay, this is a bit of a tangent but trust me, it’s going to be relevant…</p>

<p>Most of the time it’s a very good thing that browsers cache external CSS files. But if you’ve made a change to that CSS file, then that feature becomes a bug: you need some way of telling the browser that the CSS file has been updated. The simplest way to do this is to change the name of the file so that the browser sees it as a whole new asset to be cached.</p>

<p>You <em>could</em> use query strings to do this cache-busting but <a href="http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/">that has some issues</a>. I use a little bit of Apache rewriting to get a similar effect. I point browsers to CSS files like this:</p>

<pre><code>&lt;link rel="stylesheet" href="/css/main.20150310.css"&gt;
</code></pre>

<p>Now, there isn’t actually a file named <code>main.20150310.css</code>, it’s just called <code>main.css</code>. To tell the server where the <em>actual</em> file is, I use this rewrite rule:</p>

<pre><code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+).(d+).(js|css)$ $1.$3 [L]
</code></pre>

<p>That tells the <em>server</em> to ignore those numbers in JavaScript and CSS file names, but the <em>browser</em> will still interpret it as a new file whenever I update that number. You can do that in a <code>.htaccess</code> file or directly in the Apache configuration.</p>

<p>Right. With that little detour out of the way, let’s get back to the issue of inlining critical CSS.</p>

<h3>Differentiating repeat visits</h3>

<p>That number that I’m putting into the filenames of my CSS is something I update in my Twig template, like this (although this is really something that a Grunt task could do, I guess):</p>

<pre><code>{% set cssupdate = '20150310' %}
</code></pre>

<p>Then I can use it like this:</p>

<pre><code>&lt;link rel="stylesheet" href="/css/main.{{ cssupdate }}.css"&gt;
</code></pre>

<p>I can also use JavaScript to store that number in a cookie called <code>csscached</code> so I’ll know if the user has a cached version of this revision of the stylesheet:</p>

<pre><code>&lt;script&gt;
document.cookie = 'csscached={{ cssupdate }};expires="Tue, 19 Jan 2038 03:14:07 GMT";path=/';
&lt;/script&gt;
</code></pre>

<p>The absence or presence of that cookie is going to be what determines whether the user gets inlined critical CSS (a first-time visitor, or a visitor with an out-of-date cached stylesheet) or whether the user gets a good ol’ fashioned external stylesheet (a repeat visitor with an up-to-date version of the stylesheet in their cache).</p>

<p>Here are the steps I’m going through:</p>

<p>First of all, set the Twig <code>cssupdate</code> variable to the last revision of the CSS:</p>

<pre><code>{% set cssupdate = '20150310' %}
</code></pre>

<p>Next, check to see if there’s a cookie called <code>csscached</code> that matches the value of the latest revision. If there is, great! This is a repeat visitor with an up-to-date cache. Give ‘em the external stylesheet:</p>

<pre><code>{% if _cookie.csscached == cssupdate %}
&lt;link rel="stylesheet" href="/css/main.{{ cssupdate }}.css"&gt;
</code></pre>

<p>If not, then dump the critical CSS straight into the <code>head</code> of the document:</p>

<pre><code>{% else %}
&lt;style&gt;
{% include '/css/critical.css' %}
&lt;/style&gt;
</code></pre>

<p>Now I still want to load the full stylesheet but I don’t want it to be a blocking request. I can do this using JavaScript. Once again it’s Filament Group to the rescue with their <a href="https://github.com/filamentgroup/loadcss">loadCSS script</a>:</p>

<pre><code> &lt;script&gt;
    // include loadCSS here...
    loadCSS('/css/main.{{ cssupdate }}.css');
</code></pre>

<p>While I’m at it, I store the value of <code>cssupdate</code> in the <code>csscached</code> cookie:</p>

<pre><code>    document.cookie = 'csscached={{ cssupdate }};expires="Tue, 19 Jan 2038 03:14:07 GMT";path=/';
&lt;/script&gt;
</code></pre>

<p>Finally, consider the possibility that JavaScript isn’t available and link to the full CSS file inside a <code>noscript</code> element:</p>

<pre><code>&lt;noscript&gt;
&lt;link rel="stylesheet" href="/css/main.{{ cssupdate }}.css"&gt;
&lt;/noscript&gt;
{% endif %}
</code></pre>

<p>And we’re done. Phew!</p>

<p>Here’s how it looks all together in my Twig template:</p>

<pre><code>{% set cssupdate = '20150310' %}
{% if _cookie.csscached == cssupdate %}
&lt;link rel="stylesheet" href="/css/main.{{ cssupdate }}.css"&gt;
{% else %}
&lt;style&gt;
{% include '/css/critical.css' %}
&lt;/style&gt;
&lt;script&gt;
// include loadCSS here...
loadCSS('/css/main.{{ cssupdate }}.css');
document.cookie = 'csscached={{ cssupdate }};expires="Tue, 19 Jan 2038 03:14:07 GMT";path=/';
&lt;/script&gt;
&lt;noscript&gt;
&lt;link rel="stylesheet" href="/css/main.{{ cssupdate }}.css"&gt;
&lt;/noscript&gt;
{% endif %}
</code></pre>

<p>You can see the production code from The Session <a href="https://gist.github.com/adactio/8a15bcdfef855bca16ed">in this gist</a>. I’ve tweaked the <code>loadCSS</code> script slightly to match my preferred JavaScript style but otherwise, it’s doing exactly what I’ve outlined here.</p>

<h3>The result</h3>

<p>According to <a href="https://developers.google.com/speed/pagespeed/insights/?url=https%3A%2F%2Fthesession.org">Google’s PageSpeed Insights</a>, I done good.</p>

<p><a href="https://adactio.com/notes/8448"><img src="https://adactio.com/images/uploaded/8448/medium.png" alt="Optimising https://thesession.org/"/></a></p>
