Custom TTF fonts loading slowly in React app

Chris Lau

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;
}

Ali Mousavi

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).


Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related