Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using preload with Create React App

I'm trying to use preload for a font in a project that was bootstrapped with create-react-app.

I added this tag to my index.html file:

<link rel="preload" href="%PUBLIC_URL%/myFontFile.woff2" as="font" type="font/woff2">

But my problem is that I don't know how to reference this font file from my CSS (in the @font-face url). The CSS file is not in the public folder.

A different option might be to put the font file into /src but then I don't know what the file name of my font file is in the preload tag because it gets assigned a random id when there is a new version of it & webpack builds the project.

I know that I can put the CSS together with the font file into the public folder but that will mean that this CSS doesn't get bundled.

What is the best approach to get preload to work with create-react-app (no eject) and have the CSS with the @font-face declaration bundled together with the other CSS files?

Or if this is not really possible: what are my alternatives where I can get a similar behaviour to preload for my font loading?

like image 393
maracuja-juice Avatar asked Jul 30 '26 01:07

maracuja-juice


1 Answers

You should check out this article from CSS tricks for font optimization first, but I believe your font should be in your public dir when using create react app. I use mine along with the LoadCSS library

<link rel="preload" href="./style/Atlan-Bold.woff" as="font" type="font/woff2" onload="this.onload=null;this.rel='stylesheet'" crossorigin>

directly after this call I have my css file which references this font as so:

<link rel="preload" href="./style/style.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="./style/style.css"></noscript>

and in this css I reference

@font-face {
  font-family: 'Atlan Bold';
  src: url('Atlan-Bold.woff') format('woff')
}

additionally here is some info for using in Chrome: Preloading fonts in Chrome with 'preload' link directive

like image 77
TheFastCat Avatar answered Aug 01 '26 08:08

TheFastCat