Loading

Optimizing CSS Delivery

How to optimize delivery of CSS assets to improve your page speed.

Barnabas Nomo | Fri, January 26th 2018


Building a good score of Google's pagespeed insights is one good way of getting your site noticed. Aside that, being able to serve content in the shortest possible time is also important because you should not keep your users waiting so long. 

One optimization suggestion that google usually gives is the Elimination of render-blocking Javascript and CSS in the above-the-fold content.

Here is a simple javascript function I use to optimize delivery of my CSS files.

Assuming I have an html webpage that loads the following resources.

<link rel="stylesheet" href='/stylesheets/bootstrap.min.css'>
<link rel="stylesheet" href="/stylesheets/bootstrap-theme.min.css">
<link rel="stylesheet" href='/stylesheets/font-awesome.min.css'>
<link rel="stylesheet" href='https://fonts.googleapis.com/css?family=Open+Sans:400,400i,600,700,700i'>
<link rel="stylesheet" href='https://fonts.googleapis.com/css?family=Crimson+Text:400,700,700i|Josefin+Sans:700'>
<link rel="stylesheet" href='/stylesheets/owl.theme.default.min.css'>
<link rel="stylesheet" href='/stylesheets/owl.carousel.min.css'>
<link rel="stylesheet" href='/stylesheets/main.css'>

I can simply optimize deliver by putting the following snippet at the bottom of my page

<script>
     var cb = function (href) {
        var l = document.createElement('link');
        l.rel = 'stylesheet';
        l.href = href;
        var h = document.getElementsByTagName('head')[0];
        h.appendChild(l);
    };
    cb('/stylesheets/bootstrap.min.css');
    cb("/stylesheets/bootstrap-theme.min.css");
    cb('/stylesheets/font-awesome.min.css');
    cb('https://fonts.googleapis.com/css?family=Open+Sans:400,400i,600,700,700i');
    cb('https://fonts.googleapis.com/css?family=Crimson+Text:400,700,700i|Josefin+Sans:700')
    cb('/stylesheets/owl.theme.default.min.css')
    cb('/stylesheets/owl.carousel.min.css')
    cb('/stylesheets/main.css');
</script>