Reduce Google Fonts file size by more than 80%

David Ojeda - Oct 1 '20 - - Dev Community

Sometimes we only need a font for a couple of words, like a logo or slogan. Why do we download the whole font file if we only need a few letters?

In this post, I'll show you how you can reduce your font file size by more than 80%. This size reduction will be more effective the fewer characters you need.

Base HTML

This is the base HTML we'll use. It contains the Roboto font and two headers. One with Roboto font-family and the other with the default font:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link href="https://fonts.googleapis.com/css2?family=Roboto" rel="stylesheet">

</head>
<body>
  <h1 style="font-family: 'Roboto', sans-serif;">David Ojeda</h1>
  <h2>Default font</h2>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Measuring current font file size

If you open this file with your browser and open the network tab of the Developer Console, you would see this:

Developer console

~657 bytes for the Google Fonts API call and ~11.1 kB for the actual Roboto font.

If you look at the HTML again, you can notice that we're only using the font for my name, David Ojeda. What if we could download only those letters? It turns out we can.

Changing the font URL

We need to change the font URL from this:

<link href="https://fonts.googleapis.com/css2?family=Roboto" rel="stylesheet">
Enter fullscreen mode Exit fullscreen mode

to this:

<link href="https://fonts.googleapis.com/css2?family=Roboto&text=David%20Ojeda" rel="stylesheet">
Enter fullscreen mode Exit fullscreen mode

What's new? The &text= URL parameter. We'll only download the characters we need. Just remember, the text parameter value:

  • Is case-sensitive.
  • Needs to be URL encoded.

Measuring updated font file size

Let's measure the size of the file now:

Developer console

~359 bytes for the Google Fonts API call and ~1.3 kB for the actual Roboto font. That's like 89% file reduction for the font!

Wrap up

I found this implementation in the Google Fonts documentation days ago, and I wanted to share it so more people know about it.

It saved me this 80-90% file size on my personal finance blog, and I'm sure it can help others do the same.

Thanks for reading me! đź’™

. . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player