Skip to content

Instantly share code, notes, and snippets.

@davidbgk davidbgk/index.html
Last active Sep 26, 2017

What would you like to do?
Dealing with (non)critical CSS, the progressive enhancement way
<!doctype html><!-- This is a valid HTML5 document. -->
<meta charset=utf-8><!-- Better(?) to include encoding before the <title>. -->
<title>Test template</title><!-- Required to make a valid HTML5 document. -->
<link rel=icon href="data:;base64,iVBORw0KGgo="><!-- Blank gif, avoids an extra query. -->
/* Critical CSS only: above the fold, positionning and so on. */
p { background-color: red; }
<!-- Preload the not critical CSS for future usage. -->
<link rel=preload href=not-critical.css as=style onload="this.rel='stylesheet'">
<!-- In case JS is not activated/blocked, we fallback on regular CSS declaration. -->
<noscript><link rel=stylesheet href=not-critical.css></noscript>
<!-- That's it, we can fire our content right away! -->
<p>Hello World!
/* Progressive enhancement: cutting the mustard.
See */
if ('devicePixelRatio' in window) {
/* Credits: */
function loadJS (src, callback) {
const ref = document.getElementsByTagName('script')[0]
const script = window.document.createElement('script')
script.src = src
script.async = true
script.onload = callback
/* You may wonder why not simpler `document.head.appendChild(script)`
See */
ref.parentNode.insertBefore(script, ref)
/* Credits: */
loadJS('', _ =>
loadJS('', _ =>
console.log('Non-critical CSS loaded via loadCSS.')

This comment has been minimized.

Copy link

rik commented Jun 6, 2017

This can be made more performant by concatenating loadcss and cssrelpreload. loadJS can also be simplified given that you cut the mustard before:

if (!'devicePixelRatio' in window) {

function loadJS(src, callback) {
    const script = document.createElement('script')
    script.src = src
    script.async = true
    script.onload = callback

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.