Prefetch your Google Fonts for Performance Gains in Gatsby
Why is Google Fonts an issue?
The cost of using a call such as
@import url('https://fonts.googleapis.com/css?family=Lato:300,400,900');
is that the browser first has to download the CSS file, and parse it. Afterwards, the browser downloads your fonts. This process is particularly syncronous, so we can't download your fonts until we ask Google for the location of the font files we need.
How do we speed things up?
We can get a large performance boost by self-hosting our fonts. To do this, you would need to:
- Use google-webfonts-helper to figure out which fonts you needed to download
- Check them into your repo
- Reference them in your CSS
- Ensure that CSS is in-lined in your HTML, and among the first CSS to be read by browsers
This is a bit involved, but totally worth it. At a previous employer I managed to shave 300ms off of page load time by self-hosting fonts.
Enter gatsby-plugin-prefetch-google-fonts
Now with gatsby-plugin-prefetch-google-fonts, you can save 3-400ms with a little bit of configuration.
- Install:
yarn add gatsby-plugin-prefetch-google-fonts
- Configure
gatsby-config.js
:
{ resolve: `gatsby-plugin-prefetch-google-fonts`, options: { fonts: [ { family: `Lato`, variants: [`300`, `400`, `900`], }, ], }, },
Results
Before:
If you look at the time spent by Resource 8, 10, and 11, you can see we're waiting quite a bit just to get the page's fonts loaded.
It's also not the first thing the browser does, so we're likely going to see a flash of missing font. This also depends on what your font-display
setting is in CSS.
After:
After adding the prefetch plugin, we can see Resource 2, 3, and 4 being immediately loaded once we fetch the page.
I was so impressed with these results that I wrote this blog post!
(Shameless plug for the useEffect book I wrote below)
Tired of infinite re-renders when using useEffect?
A few years ago when I worked at Atlassian, a useEffect bug I wrote took down part of Jira for roughly one hour.
Knowing thousands of customers can't work because of a bug you wrote is a terrible feeling. To save others from making the same mistakes, I wrote a single resource that answers all of your questions about useEffect, after teaching it here on my blog for the last couple of years. It's packed with examples to get you confident writing and refactoring your useEffect code.
In a single afternoon, you'll learn how to fetch data with useEffect, how to use the dependency array, even how to prevent infinite re-renders with useCallback.