Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 16, 2022 11:42 am GMT

Preload Fonts

Usually, fonts are either downloaded from a third-party source, such as Google Fonts, or from a file that is stored in the build folder.

After running the build we get a static folder that houses 2 folders: js, css.
If we downloaded some font files they will be inside a third folder: media.

We can manually download them, or download a npm package, like @fontsource, that inside it has the files.

The browser will then load those at its own pace, but that will probably cause a UI flicker of the default browser fonts and then the desired fonts.

For a better UI feel, we have to tell the browser to preload them.

In order to achieve that we need to add a link tag that preloads the href it's given:

<linkrel="preload"href="https://fonts.gstatic.com/s/poppins/v20/pxiEyp8kv8JHgFVrJJfecnFHGPc.woff2"as="font"crossOrigin="anonymous"/>

But how do I know what to put inside the href?

For that, we need to open the network tab in the dev tools, see what the browser loads, and copy it :)

Font url in the network tab in dev tools

To locate the font request, choose the Font filter at the top.

If we are using React we can add this link tag to the index.html (just like in Vanilla JS) or inside our App.tsx, but to access the head tag from App.tsx we'll need to use the help of the react-helmet-async library.
All it does is insert its children to the head tag.
And of course, instead of "dirting" our App.tsx with more code, we can wrap it in a separate component - <PreloadFonts />

This nav bar, for example, will look like this for a split second (the gif is slowed down for a better look at the change).

UI flicker when not preloading

But after preloading the font we get no flicker:

After preloading

The same process applies to the fonts that come from a library or font files that we downloaded, the only difference is that the href will be relative, likeso:

<linkrel="preload"href="/static/media/libre-franklin-latin-400-normal.woff2"as="font"type="font/woff2"crossOrigin="anonymous"/>

Now my question is why not all fonts are preloaded automatically if there is an evident UI flicker?!

Funny meme from friend where Joe says why god?!


Original Link: https://dev.to/danielbellmas/preload-fonts-2jh7

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To