Gatsby: Fonts best practice for loading fonts

Created on 14 Dec 2018  路  3Comments  路  Source: gatsbyjs/gatsby

What is the best way to load fonts in Gatsby? I currently just import the typeface into my component like this:

import "typeface-pacifico"
import "typeface-raleway"
import "typeface-open-sans"

I wonder if there is a better way, as i get Minimize Critical Requests Depth in Lighthouse.

question or discussion

All 3 comments

Hi! 馃憢
Using self-hosted fonts is better than Google fonts, so that's a good start.

You should import the fonts in your _Layout_ component (the one that wraps all pages). Other than that you don't have to do anything else. You could also preload them (as seen here) but I personally don't see the need for that.

Slightly unrelated note:
It's pretty common to use maximum two typefaces (from a design standpoint) so maybe you can even get rid of one.

Thanks @LekoArts!

This is how I ended doing it in a dynamic way in gatsby-ssr.js. If anyone wants to turn it into a gatsby plugin, feel free.

const React = require('react')
const fs = require('fs')

exports.onRenderBody = ({ setHeadComponents }) => {

  const files = getFilesFromPath("./public/static", ".woff2")
  const preload = [
      'raleway-latin-400',
      'raleway-latin-700',
      'rochester-latin-400',
      'source-sans-pro-latin-400',
      'source-sans-pro-latin-700'
    ]

  setHeadComponents([
    files.map((file, i) => {
      return preload.map((font, key) => {
        const fileBeginning = file.split('-').slice(0,-1).join('-')
        if (fileBeginning === font) {
          return(
            <link
                    key={key}
                    rel='preload'
                    as='font'
                    type='font/woff2'
                    crossOrigin='anonymous'
                    href={`/static/${file}`}
                />
          )
        }
      })
    })
  ])
}

function getFilesFromPath(path, extension) {
  let dir = fs.readdirSync( path );
  return dir.filter( elm => elm.match(new RegExp(`.*\.(${extension})`, 'ig')));
}

You might be interested in my proposal here: #14281

Was this page helpful?
0 / 5 - 0 ratings