I'm trying to include a custom font in my React app (made with create-react-app). It seems to be somewhat working but only after 2-3 second after loading the page. Until then, the text appears to use the browser's default font (like Times New Roman), and then swaps to the custom font after a few seconds. Can someone please explain to me why this is happening and what I need to do to fix this?
I'm importing the font into my top-level App.js
file like so:
import './fonts/tarrgetital.ttf';
import './App.scss';
And have it declared in my App.scss
file like so:
@font-face {
font-family: 'tarrgetital';
src: local('tarrgetital'), url(./fonts/tarrgetital.ttf) format('truetype');
}
h2 {
font-family: tarrgetital;
}
The delay in loading the web fonts is an expected behaviour issue and it's happening because the browser load the fonts when it detects a DOM element with a CSS selector that matches the font-face rule and that happens when then HTML file and all the CSS files have been downloaded on the client. It's a lazy loading mechanism. There are some solutions to improve this behavior:
Use optimized web font file:
For better performance, you can swap your TTF
font file in the font-face with the woff
and woff2
file formats. these formats are compressed in gzip thus reducing the file size and initial downloading time on the client. If those formats are not available you can use one of many online tools to convert the font file (google TTF to woff2
).
Webpack Preload:
In webpack 4.6.0+ you can preload modules. this uses the preload
hint in HTML link tags (<link rel="preload">
). it will tell the browser to preload the resource before downloading the rest of the resources. To use this option replace import './fonts/tarrgetital.ttf';
with import(/* webpackPreload: true */ './fonts/tarrgetital.ttf');
More on webpack preload here: https://webpack.js.org/guides/code-splitting/#prefetchingpreloading-modules and more info on HTML preload hint here: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments