Blog

How to make loading google fonts faster on Gatsby

December 14, 2020

How to make loading google fonts faster on Gatsby

Why to use fonts prefetching?

You need to preload fonts that you are using to decrease time to FMP(first meaningful paint).

How to use it?

Earlier was very popular plugin gatsby-plugin-prefetch-google-fonts. But now it’s deprecated and may cause this error:

ENOENT: no such file or directory, stat '.cache/google-fonts//fonts'

Solution

You can replace gatsby-plugin-prefetch-google-fonts with gatsby-plugin-preload-fonts. And gatsby-plugin-preload-fonts is the official plugin for fonts preloading from Gatsby. The main difference from old plugin is that it loads fonts by scraping your site, not from the gatsby-config.

  1. Remove old plugin
  2. Add to css or template import of your fonts
  3. Install plugin using the steps from official guide:
npm install gatsby-plugin-preload-fonts

then add scraping command to package.json:

{
  "scripts": {
    "preload-fonts": "gatsby-preload-fonts"
  }
}

add plugin to gatsby-config:

module.exports = {
  plugins: [`gatsby-plugin-preload-fonts`],
}

run your site on localhost:

gatsby develop

and then start scraping:

npm run preload-fonts

All scraping results would appear in console and saved in font-preload-cache.json.

Then, reload your develop instance and enjoy!


Want some more awesome themes?