In a “daily tip” a couple of days ago, the excellent Chris Ferdinandi recommended an approach to loading CSS asynchronously based on a refined technique by Scott Jehl. The short of it is that you load your stylesheets like this:
<link rel="stylesheet" href="/path/to/my.css" media="print" onload="this.media='all'">
You see what that’s doing? It’s loading the stylesheet for the print medium, but then when the document finishes loading it’s switching the media type from “print” to “all”. Because it didn’t apply to begin with the stylesheet isn’t render-blocking. You can use this to delay secondary styles so the page essentials can load at full speed.
I don’t like this approach. I mean: I love the elegance… I just don’t like the implications.
In principle, it’s this:
- Link your stylesheet from within a
<noscript lazyload>(if you’re a standards purist, you might prefer to use a
<noscript>blocks and reinject them. In modern browsers, this is as simple as e.g.
If you need support for Internet Explorer, you need a little more work, because Internet Explorer doesn’t expose
<noscript> blocks to the DOM in a helpful way. There are a variety of possible workarounds; I’ve implemented one but not put too much thought into it because I rarely have to think about Internet Explorer these days.
In any case, I’ve implemented a proof of concept/demonstration if you’d like to see it in action: just take a look and view source (or read the page) for details. Or view the source alone via this gist.