Google Fonts is one of the easiest way to customize your website. Pick your fonts, add few lines of html, and boom, you're done:
<head>
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"
rel="stylesheet"
/>
</head>
Well, until you realize that your fonts aren't getting applied immediately, only happening after the whole page has been loaded. That improves page speed but isn't the best design wise (and to some extent, UX wise).
We can tell the browser to load assets before load with rel="preload"
:
<head>
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"
rel="preload"
as="style"
crossorigin
/>
<link
href="https://fonts.googleapis.com/css2?family=Roboto&display=swap"
rel="stylesheet"
/>
</head>
Make sure to add both of the <link/>
tag.
But this doesn't solve our problem just yet. We're preloading a stylesheet, but that stylesheet also imports fonts. We have to preload those as well.
If you visit https://fonts.googleapis.com/css2?family=Roboto&display=swap
(the stylesheet location), you'll see a list of font-face declaration:
/* latin */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
That url inside url(https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2)
is the actual font and we can preload those as well:
<head>
<!-- previous stuff -->
<link
rel="preload"
href="https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2"
crossorigin
as="font"
type="font/woff2"
/>
</head>
You only have to do this for @font-face
with a /* latin */
or /* latin-ext */
comment since those are the font files for the English alphabet.
This won't be perfect but it should work 95% of the time.
Cheers!
Top comments (0)