SJ (Scott Jehl)

Let's Standardize Async CSS!

photo of scott jehl profile headshot

By Scott Jehl

6 years back I posted the Simplest Way to Load CSS Asynchronously to document a hack we'd been using for at least 6 years prior to that. The use case for this hack is to load CSS files asynchronously, something that HTML itself still does not support, even though script elements have supported both defer and async attributes for quite some time. The hack takes advantage of browsers' built-in behavior of loading CSS asynchronously whenever a stylesheet is referenced using a media type or query that doesn't match the browsing conditions, which is the opposite of the default stylesheet loading behavior, which is synchronous and render-blocking. Typically, that default blocking behavior is what you want, but when you do want async CSS, there's a way to take advantage of that non-matching media loading behavior: you can give the link element a non-matching media type and an onload handler that sets it back to screen or all when the stylesheet loads.

Like so:

<link rel="stylesheet" href="site.css" media="print" onload="this.media='all'">

This works, and it's effective enough that many performance guides from Google and such recommend it. But it has a major downside: that onload handler relies on JavaScript to apply the CSS to the page. It's a hack, and even if it works well, I think it's long past time we get this behavior standardized.

The link element should support an async attribute, like this:

<link rel="stylesheet" href="site.css" async>

Over at the HTML living standard's issue tracker, I've chimed in to say as much and volunteer helping out if I can.

Here's the issue and my comment: https://github.com/whatwg/html/issues/3983#issuecomment-2581298073

If you agree, I'd love to see folks chime in with a +1. Thanks!