media="print"
and onload
The filament group recently (July 2019) published an article giving their latest recommendation for how to load CSS asynchronously. Even though they are the developers of the popular Javascript library loadCSS, they actually recommend this solution that does not require a Javascript library:
<link
rel="stylesheet"
href="/path/to/my.css"
media="print"
onload="this.media='all'; this.onload = null"
>
Using media="print"
will indicate to the browser not to use this stylesheet on screens, but on print. Browsers actually do download these print stylesheets, but asynchronously, which is what we want. We also want the stylesheet to be used once it is downloaded, and for that we set onload="this.media='all'; this.onload = null"
. (Some browser will call onload
twice, to work around that, we need to set this.onload = null
.) If you want, you can add a <noscript>
fallback for the rare users who don't have Javascript enabled.
The original article is worth a read, as it goes into more detail than I am here. This article on csswizardry.com is also worth a read.