Search code examples
gatsbystyled-componentsapple-m1

GatsbyJS not loading google fonts after initial load


I upgraded Gatsby from v2.x.x to 3, and like the documentation suggested, upgraded all the gatsby plugins including gatsby-plugin-styled-components as well as styled-components.

I understand that I've upgraded major versions, which means there will be breaking changes, but I had to upgrade Gatsby as it breaks on an M1 macbook.

Problem now is, my website https://nikhilvijayan.com now doesn't load the google fonts. For eg: the first load works OK (i.e. google fonts load OK), but then clicking on any of the links in the Nav (for eg: https://nikhilvijayan.com/projects) loads the page without any google fonts - however, refreshing the page will then load in the google fonts.

I haven't done much front-end recently, and was wondering if someone could point me in the right direction to debug this issue please? Is there some kind of a race condition happening here?

Luckily, this is happening when I run the app locally as well, so at least this is consistent behaviour.

Github repo: https://github.com/nkhil/portfolio

An example of styled-components use: https://github.com/nkhil/portfolio/blob/main/src/components/Hero.js#L47


Solution

  • I think your fonts are loaded on the initial rendering properly but get lost in each because the @font-face support is quite odd (see GitHub issue) in styled-components. There are a bunch of articles that recommend using a font.css file.

    My proposed solution is to add the fonts using a font.css file, where you define your @font-face, imported directly in the Layout component (because it's shared across your templates), or using a Helmet component to load the fonts but only in the Layout, you don't need to use it in all the components which will lead into a decrease of performance.

    You can even combine both approaches with:

    <Helmet>
      <link rel="stylesheet" type="text/css" href="/fonts.css" />
    </Helmet>