Defer Loading CSS Files to Reduce Page Loading Time

by

Page load time is one of the critical things for your visitors, and equally important for search engines. When including multiple JavaScript and CSS files, browser has to wait until all those files have been downloaded in order to render the page.

Depending upon connection speed, it may take several seconds to fully load all resources and visitor has to sit idle till that time.

The technique we are discussing here will allow the browser to show HTML page initially without any style, so the visitor can at least start reading the content. As soon as page is loaded, style-sheet will be loaded and applied without blocking main thread. It’s similar to defer loading social media buttons.

You may think why one should expose the ugly look of page without loading styles! That’s correct, even that will make a bad impression. So, the best approach could be including critical CSS code needed to style the above-the-fold content in HTML page itself (under head section of webpage), and loading non-critical or large files by using below method.

Async CSS Loading

We can make use of simple JavaScript function to solve our purpose. Below is an example to load single style sheet after page is loaded.

<script>
//define function to load css
var loadCss = function(){
	var cssLink = document.createElement('link');
    cssLink.rel = 'stylesheet';
    cssLink.href = 'myawesomestyle.css';
    var head = document.getElementsByTagName('head')[0];
    head.parentNode.insertBefore(cssLink, head);
};

//call function on window load
window.addEventListener('load', loadCss);
</script>

Loading Multiple Stylesheets

To make it easy, we will parameterize the loadCss function to accept file path. And then, we will define our master function that will call above function repetitively for every single file.

<script>
var loadMultipleCss = function(){
	//load local stylesheet
	loadCss('myawesomestyle.css');
    
    //load Bootstrap from CDN
    loadCss('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css');
    
    //load Bootstrap theme from CDN
    loadCss('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css');
}

var loadCss = function(cssPath){
	var cssLink = document.createElement('link');
    cssLink.rel = 'stylesheet';
    cssLink.href = cssPath;
    var head = document.getElementsByTagName('head')[0];
    head.parentNode.insertBefore(cssLink, head);
};

//call function on window load
window.addEventListener('load', loadMultipleCss);
</script>

Before and after applying this tweak, compare your page speed score. There are services which automatically take care of these optimizations to boost your PageSpeed score even up to 100 and bring down the loading time to just a few milliseconds by optimizing CSS, JS, Images, Fonts etc.

If you face any problem in implementing this, do post in comments. I’ll try to reply.