Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preloading Google Fonts and CLS

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

like image 593
Glutch Avatar asked Nov 06 '22 03:11

Glutch


People also ask

Should you preload Google Fonts?

Without the 'preload', the browser won't download the font until it finds HTML in the page that matches a CSS rule which uses the font. In other words, it may be quite some time before the browser tries to download the font. So it's worth using 'preload' whether the font is served from your own domain or not!

Should I preload all fonts?

If you load unnecessary fonts, you'll unnecessarily delay a visitor's browser from loading the rest of your site. To balance these trade-offs, you should limit the number of fonts that you preload to only those that are absolutely necessary for the initial page load (i.e. those fonts that are needed above the fold).

Should I load Google Fonts locally?

The actual load time of your website will suffer if you host Google Fonts locally. Google uses the best-in-class web performance technologies to serve fonts.


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

like image 177
Marsellus Avatar answered Nov 12 '22 16:11

Marsellus