title: Run code after deferred CSS is loaded
body: <p>The following snippet is provided in <a href="//developers.google.com/speed/docs/insights/OptimizeCSSDelivery" rel="nofollow noreferrer">Google PageSpeed Tools - Insights - Optimize CSS Delivery</a> which suggests that this should be used to defer loading of less important external stylesheets until after the initial render.  </p>
  
  <p>How can I run a piece of code after those CSS files have successfully loaded?</p>
  
  <pre><code> &lt;html&gt;
    &lt;head&gt;
      &lt;style&gt;
        .blue{color:blue;}
      &lt;/style&gt;
      &lt;/head&gt;
    &lt;body&gt;
      &lt;div class="blue"&gt;
        Hello, world!
      &lt;/div&gt;
      &lt;noscript id="deferred-styles"&gt;
        &lt;link rel="stylesheet" type="text/css" href="small.css"/&gt;
      &lt;/noscript&gt;
      &lt;script&gt;
        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 = requestAnimationFrame || mozRequestAnimationFrame ||
            webkitRequestAnimationFrame || msRequestAnimationFrame;
        if (raf) raf(function() { window.setTimeout(loadDeferredStyles, 0); });
        else window.addEventListener('load', loadDeferredStyles);
      &lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>