Skip to content

Instantly share code, notes, and snippets.

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

Embed
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. -->
<style>
/* Critical CSS only: above the fold, positionning and so on. */
p { background-color: red; }
</style>
<!-- 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!
<script>
/* Progressive enhancement: cutting the mustard.
See https://sixtwothree.org/posts/cutting-the-mustard-revisited */
if ('devicePixelRatio' in window) {
/* Credits: https://github.com/filamentgroup/loadJS */
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 https://www.paulirish.com/2011/surefire-dom-element-insertion/ */
ref.parentNode.insertBefore(script, ref)
}
/* Credits: https://github.com/filamentgroup/loadCSS */
loadJS('https://unpkg.com/fg-loadcss@1.3.1/src/loadCSS.js', _ =>
loadJS('https://unpkg.com/fg-loadcss@1.3.1/src/cssrelpreload.js', _ =>
console.log('Non-critical CSS loaded via loadCSS.')
)
)
}
</script>
@rik

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) {
    return
}

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

loadJS('loadcss-and-cssrelpreload.js')
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.