Blog

Tag: PageSpeed Insights

PageSpeed Insights: Removing Render-blocking CSS

If you write javascript which dynamically loads CSS files on your page, you have probably seen PageSpeed Insights complain to you about removing render-blocking CSS. Fixing render-blocking javascript is relatively easy: just add an async attribute to the script, and include it before the closing body tag, or use an async loader like Google Analytics. Fixing render-blocking CSS is a little trickier. We employ a little media query magic to get the job done.

// append css dynamically to head
var head = document.getElementsByTagName('head');
var element = document.createElement('link');
element.rel = 'stylesheet';
element.type = 'text/css';
element.href = '//www.my-external-css.com/my.css';

//here's the magic
element.media = 'non-existant-media';
head.appendChild(element, head.firstChild);
setTimeout(function () {
    element.media = 'all';
});

Continue reading