Skip to content

Instantly share code, notes, and snippets.

Last active August 9, 2020 17:50
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Lazy-loading CSS without introducing a mandatory JS dependency; see for more or for discussion
// This version works with modern browsers
function lazyLoadCSS(){
(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';
} 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++){
// Trigger lazyLoadCSS after the page has loaded
if (document.readyState != 'loading') {
} 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();
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment