A place to cache linked articles (think custom and personal wayback machine)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

hace 5 años
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. title: Inlining critical CSS for first-time visits
  2. url: https://adactio.com/journal/8504
  3. hash_url: 70ce67ed910c56329a329c2ad194c75e
  4. <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>
  5. <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>
  6. <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>
  7. <h3>Generating the critical CSS</h3>
  8. <p>Okay. First question: how do you figure out which CSS is critical and which CSS can be deferred?</p>
  9. <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>
  10. <pre><code>grunt.initConfig({
  11. // All my existing Grunt configuration goes here.
  12. criticalcss: {
  13. dist: {
  14. options: {
  15. url: 'http://thesession.dev',
  16. width: 1024,
  17. height: 800,
  18. filename: '/path/to/main.css',
  19. outputfile: '/path/to/critical.css'
  20. }
  21. }
  22. }
  23. });
  24. </code></pre>
  25. <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>
  26. <p>Then I add it to the list of Grunt tasks:</p>
  27. <pre><code>// All my existing Grunt tasks go here.
  28. grunt.loadNpmTasks('grunt-criticalcss');
  29. grunt.registerTask('default', ['sass', etc., 'criticalcss']);
  30. </code></pre>
  31. <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>
  32. <h3>Cache-busting CSS</h3>
  33. <p>Okay, this is a bit of a tangent but trust me, it’s going to be relevant…</p>
  34. <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>
  35. <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>
  36. <pre><code>&lt;link rel="stylesheet" href="/css/main.20150310.css"&gt;
  37. </code></pre>
  38. <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>
  39. <pre><code>RewriteCond %{REQUEST_FILENAME} !-f
  40. RewriteRule ^(.+).(d+).(js|css)$ $1.$3 [L]
  41. </code></pre>
  42. <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>
  43. <p>Right. With that little detour out of the way, let’s get back to the issue of inlining critical CSS.</p>
  44. <h3>Differentiating repeat visits</h3>
  45. <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>
  46. <pre><code>{% set cssupdate = '20150310' %}
  47. </code></pre>
  48. <p>Then I can use it like this:</p>
  49. <pre><code>&lt;link rel="stylesheet" href="/css/main.{{ cssupdate }}.css"&gt;
  50. </code></pre>
  51. <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>
  52. <pre><code>&lt;script&gt;
  53. document.cookie = 'csscached={{ cssupdate }};expires="Tue, 19 Jan 2038 03:14:07 GMT";path=/';
  54. &lt;/script&gt;
  55. </code></pre>
  56. <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>
  57. <p>Here are the steps I’m going through:</p>
  58. <p>First of all, set the Twig <code>cssupdate</code> variable to the last revision of the CSS:</p>
  59. <pre><code>{% set cssupdate = '20150310' %}
  60. </code></pre>
  61. <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>
  62. <pre><code>{% if _cookie.csscached == cssupdate %}
  63. &lt;link rel="stylesheet" href="/css/main.{{ cssupdate }}.css"&gt;
  64. </code></pre>
  65. <p>If not, then dump the critical CSS straight into the <code>head</code> of the document:</p>
  66. <pre><code>{% else %}
  67. &lt;style&gt;
  68. {% include '/css/critical.css' %}
  69. &lt;/style&gt;
  70. </code></pre>
  71. <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>
  72. <pre><code> &lt;script&gt;
  73. // include loadCSS here...
  74. loadCSS('/css/main.{{ cssupdate }}.css');
  75. </code></pre>
  76. <p>While I’m at it, I store the value of <code>cssupdate</code> in the <code>csscached</code> cookie:</p>
  77. <pre><code> document.cookie = 'csscached={{ cssupdate }};expires="Tue, 19 Jan 2038 03:14:07 GMT";path=/';
  78. &lt;/script&gt;
  79. </code></pre>
  80. <p>Finally, consider the possibility that JavaScript isn’t available and link to the full CSS file inside a <code>noscript</code> element:</p>
  81. <pre><code>&lt;noscript&gt;
  82. &lt;link rel="stylesheet" href="/css/main.{{ cssupdate }}.css"&gt;
  83. &lt;/noscript&gt;
  84. {% endif %}
  85. </code></pre>
  86. <p>And we’re done. Phew!</p>
  87. <p>Here’s how it looks all together in my Twig template:</p>
  88. <pre><code>{% set cssupdate = '20150310' %}
  89. {% if _cookie.csscached == cssupdate %}
  90. &lt;link rel="stylesheet" href="/css/main.{{ cssupdate }}.css"&gt;
  91. {% else %}
  92. &lt;style&gt;
  93. {% include '/css/critical.css' %}
  94. &lt;/style&gt;
  95. &lt;script&gt;
  96. // include loadCSS here...
  97. loadCSS('/css/main.{{ cssupdate }}.css');
  98. document.cookie = 'csscached={{ cssupdate }};expires="Tue, 19 Jan 2038 03:14:07 GMT";path=/';
  99. &lt;/script&gt;
  100. &lt;noscript&gt;
  101. &lt;link rel="stylesheet" href="/css/main.{{ cssupdate }}.css"&gt;
  102. &lt;/noscript&gt;
  103. {% endif %}
  104. </code></pre>
  105. <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>
  106. <h3>The result</h3>
  107. <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>
  108. <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>