Using Google Fonts is a convenient way of loading beautiful fonts on your website, but it comes with a penalty when it comes to website speed optimization.
Running the Google Lighthouse tool, you will discover that the embedded CSS that you got from the fonts site it’s being highlighted as render-blocking.
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet">
By altering the <link>
tag a bit we can preload and eliminate this:
<link rel="preload" href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,400;0,700;1,400;1,700&display=swap" as="style" onload="this.onload=null;this.rel='stylesheet'"/>
<noscript>
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet" type="text/css"/>
</noscript>
It all comes to 3 changes.
- We added
rel="preload"
to our code do the browser starts loading the font before it’s being called. - We used
onload
attribute to restore therel="stylesheet"
definition. - We added
<noscript>
tag as a fallback in case the browser does not use JavaScript.
I want to thank Claudiu that posted an updated version of Lucas Vazquez’s solution here.