Self hosting Google Fonts for improved performance

Posted on

Google Fonts is a great service offering hundreds of high-quality fonts available over a fast and reliable CDN.

To use them though requires the cost of opening new TCP connections. DNS resolution, TCP handshakes, and TLS negotiation to both https://fonts.googleapis.com (for the CSS) and https://fonts.gstatic.com (for the fonts) add up and can be slow on browsers/devices with high-latency connections.

If your own site is hosted on a CDN (as it should be!) you can improve font-loading performance by self hosting fonts and the respective CSS on the same domain as your content.

The ‘Download family’ option on the Google Fonts site unfortunately only downloads the font in TTF format - so isn’t suitable for modern websites.

Instead we can use the google-webfonts-helper site to download the web-friendly fonts needed.

Google Webfonts Helper

  1. Go to: https://google-webfonts-helper.herokuapp.com and search for the font you want.
  2. Leave the default ’latin’ charset checked
  3. Select the styles you want
  4. For the CSS, choose ‘Modern Browsers’. WOFF/WOFF2 has very wide support (>99%).
  5. Click Download Files to get a ZIP with your fonts.
  6. Add the CSS to your site, but with the addition of the font-display: swap; rule. e.g.
/* roboto-regular - latin */
@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 400;
  src: local(''),
       url('../fonts/roboto-v20-latin-regular.woff2') format('woff2'),
       url('../fonts/roboto-v20-latin-regular.woff') format('woff');
  font-display: swap;
}
  1. Next, consider preloading the body font for instant loading with something like:
<link rel="preload" href="/fonts/roboto-v20-latin-500.woff2" as="font" type="font/woff2" crossorigin>
  1. Test in your browsers Dev Tools Network panel to ensure that everything is working as expected.

Summary: self-hosting Google Fonts is fast and easy to setup, improves font-loading performance and can potentially improve your site’s GDPR compliance too!

Note: be sure to check the license of the fonts before self-hosting.

You might also like

Popover CSS Inspector for Bootstrap 5

A customizable style inspector for Bootstrap Popovers

Bootstrap 5 Print Stylesheet

Optimized CSS for printing