Preloading Google Fonts and CLS

Viewed 1474

I'm preloading google fonts as follows

<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preload" href="https://fonts.googleapis.com/css2?family=Fira+Code&family=Montserrat:wght@400;500;800&display=swap" as="style">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Fira+Code&family=Montserrat:wght@400;500;800&display=swap">

However, lighthouse still gives me 151ms Cumulative Layout Shift, and i can see the font flash. Why doesn't the preloading work?

Also. If i change from display=swap to optional, lighthouse says "Fonts with font-display: optional are not preloaded". Which must mean that it is in fact not pre-loaded

1 Answers

The part of your code causing the font flash is "display=swap". It displays the browser fallback font first, then swaps to your custom font once it's received from Google Fonts.

I see your note saying display:optional won't preload. Try changing "swap" to "block" if you want an invisible block of text to hold a place for your font while it loads. "Optional" gives the user's browser permission to choose either browser default or wait for your custom font to load based on their connection. Neither will cause the font to flash.

The link below explains the values for font-display well.

https://css-tricks.com/almanac/properties/f/font-display/#values

Related