Skip to content

Instantly share code, notes, and snippets.

@adactio
Last active January 30, 2024 07:13
Show Gist options
  • Save adactio/8a15bcdfef855bca16ed to your computer and use it in GitHub Desktop.
Save adactio/8a15bcdfef855bca16ed to your computer and use it in GitHub Desktop.
Twig template for inlining critical CSS on first visits.
{% set cssupdate = '20150309' %}
{% if _cookie.csscached == cssupdate %}
<link rel="stylesheet" href="/css/global-min.{{ cssupdate }}.css">
{% else %}
<style>
{% include 'global/critical.css' %}
</style>
<script>
(function (win, doc) {
'use strict';
function loadCSS(href) {
var ss = doc.createElement('link'),
ref = doc.getElementsByTagName('script')[0],
sheets = doc.styleSheets;
ss.rel = 'stylesheet';
ss.href = href;
ss.media = 'only x';
ref.parentNode.insertBefore(ss, ref);
function toggleMedia() {
var defined,
i;
for (i = 0; i < sheets.length; i = i + 1) {
if (sheets[i].href && sheets[i].href.indexOf(ss.href) > -1) {
defined = true;
}
}
if (defined) {
ss.media = 'all';
} else {
win.setTimeout(toggleMedia);
}
}
toggleMedia();
return ss;
}
loadCSS('/css/global-min.{{ cssupdate }}.css');
doc.cookie = 'csscached={{ cssupdate }};expires="Tue, 19 Jan 2038 03:14:07 GMT";path=/';
}(this, this.document));
</script>
<noscript>
<link rel="stylesheet" href="/css/global-min.{{ cssupdate }}.css">
</noscript>
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment