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
mediaattribute is set toprint. printis 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
onloadattribute to change the link’smediatoallonce it finishes loading.