Last active
January 30, 2024 07:13
-
-
Save adactio/8a15bcdfef855bca16ed to your computer and use it in GitHub Desktop.
Twig template for inlining critical CSS on first visits.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% 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