The Leaky Cauldron Blog

A Brew of Awesomeness with a Pinch of Magic...

Self hosting Google Fonts for better caching

Self hosting Google Fonts for better caching

Just a month ago a college fresher came to me showing her newly made React app, bootstrapped using create-react-app. As we got into discussing performance, she told me that everything was almost 100 on gtmetrix.com except for Browser Caching. That was because of Google Analytics and Google Fonts. And, it's not just about browser caching, a lot of times Google Fonts have files that will probably be of no use to us. For example, extra language support. Although, not much can be done about Google Analytics, I told her a little hack that will make the Google Fonts problem disappear very easily. Since, starter kits like create-react-app and Gatsby JS provide support for caching and service workers, we're better off self hosting.

For this tutorial, we'll be assuming the following:

  • This is a create-react-app project
  • We need to include Montserrat font from Google Fonts.

Let's begin, by selecting the font on https://fonts.google.com for us that will be Montserrat.

self-hosting-google-fonts-1

Next, we copy the URL in the href attribute of the example code. Open the URL from your browser and you'll see a css file, with the code to include the font-face.

self-hosted-google-fonts-2

We see here that there are quite a few font files that the api pulled. Let's say for the purpose of this article that we don't need the Vietnamese support. So, we just copy the Latin and Cyrillic parts of the stylesheet. In the code, we see, there's a URL for the font file. We download the fonts using that URL and keep them in a local project folder. Now, all we need to do is replace the url from the cloud hosted to the relative address of the locally stored file.

src: local('Montserrat Regular'), local('Montserrat-Regular'), url(https://fonts.gstatic.com/s/montserrat/v12/JTUSjIg1_i6t8kCHKm459WlhyyTh89Y.woff2) format('woff2');

to

src: local('Montserrat Regular'), local('Montserrat-Regular'), url(../fonts/JTUSjIg1_i6t8kCHKm459WlhyyTh89Y.woff2) format('woff2');

create-react-app allows us to directly import css files, we just import our stylesheet in the javascript.

...
import './styles.css';

And, that's all we need to do, create-react-app automatically takes care of caching and service worker. This works for other package like Gatsby JS as well. That's all for this article.

Reddit icon
whatsapp icon
LinkedIn icon