Sometimes we want to load the CSS asynchronously to reduce the intial page load and you can do the same by adding media="print" onload="this.media='all'
to the link as below.
<link rel="stylesheet" href="/path/to/my.css" media="print" onload="this.media='all'">
Let’s dive into the details of the above:
- The link’s
media
attribute is set toprint
. print
is a media type that applies to print-based media or when the user tries to print the page.- By using
media="print"
, the CSS file loads asynchronously (since it’s not needed immediately for screen display). - However, we still want to apply the styles to the page for screen use.
- To achieve this, we can use the
onload
attribute to change the link’smedia
toall
once it finishes loading.
What are your thoughts on this post?
I’d love to hear from you! Click this link to email me—I reply to every message!
Also use the share button below if you liked this post. It makes me smile, when I see it.