Lcode

Speed Up Google fonts on Gatsby sites

@luisccode

25 September, 2020

In this post, I'm going to explain to you how to improve your page speed with the gatsby-plugin-prefetch-google-fonts and what's make it a better option than using a link tag in your head or a @import rule inside your CSS.

The problem

Usually, when you are building a website and you need to add some fonts from Google fonts, they recommend using a link tag like this:

<link 
  href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;700&display=swap" 
  rel="stylesheet"
>

or a CSS @import rule:

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;700&display=swap');

So when we use any of those options internally the browser has to download a CSS file with all the @font-face of your fonts and then download the actual fonts. The problem here is that this CSS file has the highest possible download priority which means that will stop the initial page render until this file has been downloaded and will affect our page speed. So how do we speed things up?

Self-host your fonts

A common solution to the above problem is self-hosting your fonts by using a tool like google-webfonts-helper and figure out which fonts you will need or using gatsby-plugin-prefetch-google-fonts which makes things easier because it does all that for us with a simple configuration.

How to use it?

Install the plugin in your project

yarn add gatsby-plugin-prefetch-google-fonts
// or
npm install gatsby-plugin-prefetch-google-fonts --save

Add your fonts to your gatsby-config.js

module.exports = {
  siteMetadata: {
    title: `Speed Up Google fonts on Gatsby sites`
  },
  plugins: [
    {
      resolve: `gatsby-plugin-prefetch-google-fonts`,
      options: {
        fonts: [
          {
            family: `Poppins`,
            variants: [`300`, `400`, `700`],
          },
        ],
        display: "swap",
      },
    },
  ]
}

After that, the gatsby-plugin-prefetch-google-fonts will automatically download all the .woff and .woff2 that you need into the public folder and link those directly to your head tag.

That's all, I hope you find this article useful, if you like it, share it with your friends or let me know what you think in the comments below

Copyright ©2020 Luis Cortes. All Rights Reserved.