Using preload with Create React App

15,754

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

Share:
15,754

Related videos on Youtube

maracuja-juice
Author by

maracuja-juice

Updated on June 04, 2022

Comments

  • maracuja-juice
    maracuja-juice almost 2 years

    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?

  • maracuja-juice
    maracuja-juice almost 6 years
    And your stylesheet is then also in the public folder? (Which is a solution that I referenced in my question but is not preferred)
  • TheFastCat
    TheFastCat almost 6 years
    I have minimal, critical css directly in the HTML header, I also have a preloaded css file from the public folder(along with the WOFF font) within the HTML body. No repeated css - just diversified/split based on need and lading requirements.