Search code examples
reactjswebfontspreloading

text loads slowly even on font preload


Some text in my page appears a few seconds later compared to another text.

I've different font files for different font-weights (taken from font squirrel's web font generator). When I load component on some click event semi-bold font appears after regular font. After some research I understood that browser only loads fonts that are needed. Para font was being used before that component was loaded so it was already loaded in the browser for use, therefore the perceived delay of semi-bold font.

I preload the semi-bold font in index.html (it's a react/vite app. <link rel="preload" href="/src/assets/barlow/barlow-semibold-webfont.woff2" as="font" type="font/woff2" crossorigin /> This loads the font before it's used(can be seen on network tab of dev tools) but the text still appears after regular font :(I think it's a little fast though).

Then I just set an element that uses that font and put it out of the screen like this in my App.jsx

      <p
        id="preload-fonts"
        style={{
          position: 'absolute',
          left: '-100vw',
          opacity: '0',
          fontFamily: 'barlowsemibold',
        }}
      >

voila it works.

I want to know why it works and why preload didn't even though it still downloaded the font before the component is loaded.

My repo component name (LoadingScreen.jsx)


Solution

  • Using preload, our custom font is downloaded, but it is not used or rendered yet. Fonts will only be fully activated when they are actually used on the page (i.e. used by actual text or invisible text [like your hack]).

    Your hack forces the browser to apply the font and render it on an invisible text, so next time when actual text appears, our font is loaded, cached and activated so it’s available to be applied instantly without any delay.

    Extra point: We can use {font-display: swap} to reduce the delay to load the text with custom font but the hack works fine and I think is the best way to ensure the text is loaded with custom font without any delay.