A. M. Douglas

Asynchronous CSS: the easy way

If you've ever looked into asynchronously handling fonts, you've probably read about FilamentGroup's method:

<link rel=preload href=/assets/css/main.css as=style onload=this.rel=stylesheet;this.type=text/css;>

It might look like a hack, but this is actually what the link rel=preload spec is intended for.

The problem is that this will do absolutely nothing in browsers which do not support link rel=preload, and that is a non-trivial number of browsers. You also can't just stick your stylesheet in a noscript element and hope for the best.

FilamentGroup offers a big solution which obviously works well, but I think I prefer a rather more simple approach.

var inertCSS = document.querySelectorAll( '[rel="preload"][as="style"]' );
var i = inertCSS.length;          
while ( i-- ){
  var css  = document.createElement( 'link' );
  css.rel  = 'stylesheet';
  css.href = inertCSS[i].href;
  ( document.head || document.getElementsByTagName( 'head' )[0] ).appendChild( css );

My solution isn't bulletproof. You still need querySelectorAll and you'll need to be careful that you check for unloaded CSS on the DOMContentLoaded event—otherwise, you run the risk of loading your stylesheet(s) twice.

Labels: ,


Post a Comment