Skip to content

Instantly share code, notes, and snippets.

@Dan-Q
Last active August 9, 2020 17:50
Show Gist options
  • Save Dan-Q/1ff0e1b3cd7153b4cf0ed3f3c29c8b7d to your computer and use it in GitHub Desktop.
Save Dan-Q/1ff0e1b3cd7153b4cf0ed3f3c29c8b7d to your computer and use it in GitHub Desktop.
Lazy-loading CSS without introducing a mandatory JS dependency; see https://danq.me/lazy-css-without-js/ for more or https://danq.me/2020/08/09/lazy-css/ for discussion
// This version works with modern browsers
function lazyLoadCSS(){
[...document.querySelectorAll('noscript[lazyload]')].forEach(ns=>ns.outerHTML=ns.innerHTML);
}
(document.readyState != 'loading') ? lazyLoadCSS() : document.addEventListener('DOMContentLoaded', lazyLoadCSS);
// This version works with modern browsers and Internet Explorer 6+
function lazyLoadCSS(){
if( ( window.navigator.userAgent.indexOf('MSIE ') + window.navigator.userAgent.indexOf('Trident/') ) > 0 ) {
// Internet Explorer doesn't allow <noscript> tags to be accessible via the DOM, so we have to re-inject manually
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'my.css';
document.head.appendChild(link);
} else {
// Non-IE browsers can find <noscript lazyload> elements in the DOM and re-inject their content
var lazyNoScripts = document.querySelectorAll('noscript[lazyload]');
for(var i = 0; i < lazyNoScripts.length; i++){
lazyNoScripts[i].outerHTML=lazyNoScripts[i].innerHTML;
}
}
}
// Trigger lazyLoadCSS after the page has loaded
if (document.readyState != 'loading') {
lazyLoadCSS();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', lazyLoadCSS);
} else {
// Internet Explorer <9 doesn't support document.addEventListener
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading') lazyLoadCSS();
});
}
<head>
<!--
load your CSS within a <noscript lazyload> block; browsers without JS will render it normally (render-blocking);
browsers with JS will use the Javascript from this gist to lazy-load it later.
-->
<link rel="preload" as="style" href="my.css">
<noscript lazyload><link rel="stylesheet" type="text/css" href="my.css"></noscript>
</head>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment