Search code examples
cssperformancepagespeed

"Optimize CSS Delivery" - Why Google uses this much code to load CSS file?


This is Google Optimize CSS Delivery page. At the bottom google suggests use this code to load CSS file at the end of the page body:

  <noscript id="deferred-styles">
      <link rel="stylesheet" type="text/css" href="small.css"/>
    </noscript>
    <script>
      var loadDeferredStyles = function() {
        var addStylesNode = document.getElementById("deferred-styles");
        var replacement = document.createElement("div");
        replacement.innerHTML = addStylesNode.textContent;
        document.body.appendChild(replacement)
        addStylesNode.parentElement.removeChild(addStylesNode);
      };
      var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
          window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
      if (raf) raf(function() { window.setTimeout(loadDeferredStyles, 0); });
      else window.addEventListener('load', loadDeferredStyles);
    </script>
  </body>

My questions is why not just use this one line to do the job? Especially we are in HTML5 world.

<link rel="stylesheet" type="text/css" href="small.css"/>
</body>

Solution

  • When a browser is parsing an HTML response, it does so line by line. And when it encounters a <link> element, it stops parsing the HTML and goes to fetch the resource set by the element's href attribute.

    What the code is doing is wrapping the CSS in a <noscript> element as a fallback, and instead of blocking the page load, making a request for the CSS after the page has finished loading. It is a way to manually give a <link> element similar behavior to the <script> element's defer attribute.