Performance: how to eliminate render-blocking CSS
December 14, 2014Last update: March 28, 2020
The problem
Periodically, I run Google PageSpeed Insights on my personal website in order to check performances.
The last run reports a low score on mobile: 71 out of 100. The main suggestion that PageSpeed gives me is to eliminate render-blocking CSS in above-the-fold content (in the head
tag, just to be more clear).
A solution
To solve this issue I wrote few lines of JavaScript and in 5 minutes the score moves up: 85 out of 100. Yes, there are margins of improvement yet, but this small change improves considerably rendering. Going in deep, I delayed loading of fonts from Google Fonts and the icons font I’m using on my website.
OK, “Talk is cheap, show me the code” (cit.). This is the script I put, before closing the body
tag.
<body>
<!-- ... -->
<script>
var CSSloader = {
add: function(/*Object*/ attr) {
var linkNode = document.createElement("link");
for(var key in attr) {
linkNode.setAttribute(key, attr[key]);
}
document.head.appendChild(linkNode);
}
};
// fonts
CSSloader.add({
"rel": "stylesheet",
"type": "text/css",
"href": "css/fonts.css"
});
// icon font
CSSloader.add({
"rel": "stylesheet",
"type": "text/css",
"href": "css/icon.css"
});
</script>
</body>
As I stated before, there are still margins of improvements. In particular, as PageSpeed suggests it is a good idea putting critical CSS rules inline on the page. It is important to keep in mind when we are coding our pages that something could go wrong, specially on a mobile environment. For instance, the load of fonts could fail for some reason and our page should be in any case readable and usable.
The complete example is available on GitHub.