Luke Lewis
Luke Lewis

Reputation: 110

Font takes a noticeable split second to load. Is there any way around this?

I'm using a google font in my react project, and whenever I open up my site, there is a very noticeable split second where my text that uses the font initially loads with a seemingly different font, then changes to the correct font right after.

What is happening here? And how do I prevent this from happening?

Loading font in public/index.html

<link
    href="https://fonts.googleapis.com/css2family=Bebas+Neue&display=swap"
    rel="stylesheet"
/>

adding the font to a class in src/index.css

.bg-header {
  font-family: "Bebas Neue", sans-serif;
  color: darkorange;
  text-decoration: underline;
  position: absolute;
  bottom: 10%;
  left: 5%;
  font-size: 75px;
}

html tag in react component

<h5 className="bg-header">{getHeader()}</h5>

Upvotes: 3

Views: 1672

Answers (2)

thomallen
thomallen

Reputation: 2034

CSS: font-display

If you really don't want the font to swap you can use:

body { 
  font-display: block;
}

Or probably a more user-friendly way is:

body { 
  font-display: fallback;
}

However, this can hurt your rankings in search engines and you should read up on why the fonts are set to swap by default. The default setting for the font-display property is auto.

You can read about the CSS font-display property here https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display.

Google Fonts display property

In your google fonts import, you can actually specify the font-display setting in the font URL:

<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">

Notice the display=swap part of the URL.

Other resources

These articles will also be very helpful:

Upvotes: 1

Spectric
Spectric

Reputation: 31992

We can use the ‘Preload’ resource hint to tell the browser that we want our font files to start downloading right away, not after the CSS is parsed. This helps loading the font faster.

Most major browsers support preload and other resource hints (Firefox is also currently in development to add this). Adding this to your HTML would look like this:

<link rel="preload" as="font" type="font/woff2" 
  href="<FONT LOCATION>" crossorigin>

Machmetrics

Upvotes: 1

Related Questions