Providing a fallback for critical-path CSS

Submitted by sonniesedge on Wed, 11/05/2014 - 11:00
tl;dr make sure you do it.

The method I recently talked about using, for loading non-critical CSS asynchronously via javascript, has one blindingly obvious fatal flaw: it fails when javascript is disabled.

Shut up.

This is why you test things, kids.

But there's a simple way around it: provide a regular link to your CSS, but wrap it in a <noscript> tag.

So, in addition to the existing LoadCSS chunk:

// Async CSS loader
  function loadCSS( href, before, media ){
    "use strict";
    var ss = window.document.createElement( "link" );
    var ref = before || window.document.getElementsByTagName( "script" )[ 0 ];
    ss.rel = "stylesheet";
    ss.href = href; = "only x";
    ref.parentNode.insertBefore( ss, ref );
    setTimeout( function(){ = media || "all";
    } );
    return ss;
  loadCSS( "/theme/dist/stylesheets/main.css" );

we just have to add:

  <link rel="stylesheet" href="/theme/dist/stylesheets/main.css">

Now the criticalpath CSS is no longer reliant on javascript executing. Just as it should be.

Show in RSS feed
Show on index pages