Search code examples
javascriptcsspagespeed

Google PageSpeed Insights with Multiple CSS Files


I'm optimizing my site based on Google's PageSpeed Insights. It recommends that I "Optimize CSS Delivery" for several files (names simplified for example's sake):

<link rel="stylesheet" href="css/app.css" type="text/css">
<link rel="stylesheet" href="css/responsive.css" type="text/css">
<link rel="stylesheet" href="css/styles.css" type="text/css">

...by moving them from <link> tags in the <head> to being called through JavaScript before the closing tag:

<script>
  var cb = function() {
    var l = document.createElement('link'); l.rel = 'stylesheet';
    l.href = 'css/app.css';
    var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
  };
  var raf = requestAnimationFrame || mozRequestAnimationFrame ||
      webkitRequestAnimationFrame || msRequestAnimationFrame;
  if (raf) raf(cb);
  else window.addEventListener('load', cb);
</script>

</body>

As you can see, only app.css is being called.

My question is, is there a way to add all three CSS files in this script?


Solution

  • You will need to extend Google's script so that you can add multiple files like this:

    var loadCSSFiles = function() {
        var links = ["style1.css", "style2.css", "style3.css"],
            headElement = document.getElementsByTagName("head")[0],
            linkElement, i;
        for (i = 0; i < links.length; i++) {
            linkElement = document.createElement("link");
            linkElement.rel = "stylesheet";
            linkElement.href = links[i];
            headElement.appendChild(linkElement);
        }
    };
    
    var raf = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame;
    if (raf) {
        raf(loadCSSFiles);
    } else {
        window.addEventListener("load", loadCSSFiles);
    }