Mastering Web Fonts Optimization: The Definitive Guide
Published: 2023-12-18 12:34:22

by [Wahab Seidu](https://blog.openreplay.com/authors/wahab-seidu)


<blockquote><em>
Web fonts are essential in web development not only for design but also for their impact on web performance. Using fonts without performance in mind can cause many issues, like slowing down a web page and temporarily displaying fonts in invisible form. This article will explain how you can get the best performance using fonts.
</em></blockquote>


<div style="background-color:#efefef; border-radius:8px; padding:10px; display:block;">
<hr/>
<h3><em>Session Replay for Developers</em></h3> 
<p><em>Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data.</em></p>
<img alt="OpenReplay" style="margin-top:5px; margin-bottom:5px;" width="768" height="400" src="https://raw.githubusercontent.com/openreplay/openreplay/main/static/openreplay-git-hero.svg" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<p><em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em><p>
<hr/>
</div>


When we hear about web fonts, we often think about the design aspect. Web designers and developers often consider the qualities of different font designs and what they are suited for. What we rarely consider is the performance dimension that web fonts introduce. 


This guide will examine web fonts from a performance perspective. You will learn about:

* The types of web fonts.
* Why web fonts matter. 
* Performance challenges associated with custom web fonts.
* Web Font Optimization Strategies.
* Tools for testing web font performance.



## Types of Web Fonts

We have three major types of web fonts:

### System Fonts

System fonts:
* are pre-installed on your device or operating system.
* are the best in performance as they do not need extra font file downloads. 
* should be used when performance is the top priority. 

Common system fonts are Helvetica, Futura, Garamond, etc.


### Web-Safe Fonts

Web-safe fonts:
* are safe to use on the web because they enjoy extensive support across various devices, browsers, and platforms.
* allow you to provide consistent typography across all browsers and devices.
* pose no performance challenges like system fonts.
* are commonly used as fallbacks when the custom fonts do not load due to performance issues.

Common web-safe fonts are Helvetica, Times New Roman, Georgia, etc.


### Custom Fonts

Custom fonts:
* are not pre-installed on the user’s device or operating system.
* are loaded externally from the local web server or a third-party service (like Adobe Typekit or Google Fonts).
* provide a wide range of typography, allowing design flexibility and freedom.



## Why Web Fonts Matter

At first glance, web fonts may seem like mere typography without much importance. Yet, web fonts serve more vital roles for our websites. Some of these roles are as follows:

* **Aesthetics**: Web fonts support the creation of attractive web interfaces. Doing this creates a positive perception of the brand or product.

* **Branding**: Custom fonts allow brands to maintain the same typography in their offline brand identity. This promotes brand recognition and trust among users.

* **User experience**: Optimized web fonts will improve page speed and content rendering. These improvements will, in turn, enhance user experience.

Although system fonts are readily available, they normally cannot deliver the desired branding for a website. System fonts lack a wide range of options for selection and customization.

Custom fonts solve this problem as they offer a wide range of typography. Unfortunately, this versatility comes at the cost of performance. Unoptimized custom fonts may affect page load and content rendering.

This article's main focus is solving the performance issues associated with using custom fonts.



## Performance Challenges Associated with Custom Web Fonts

There are several issues you must consider.

### Slower Page Load

Each custom font file attached to a webpage results in extra file downloads. This reduces page speed, as the browser must download the fonts before rendering them to the page. 

Additionally, custom font file sizes are larger than system fonts. This can also result in slower page loading.

### Render Blocking

Custom web fonts are render-blocking resources. Render-blocking resources are elements that prevent the page from loading quickly. This is because the browser has to fetch and process them before rendering the page.

When custom fonts are not optimized, processing them can cause delays, frustrating users. Other examples of render-blocking resources are JavaScript and HTML files.

This image from [7Eagles](https://the7eagles.com/eliminate-render-blocking-resources/) provides a visual illustration.

![Render-blocking](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image1.png)

In the above image, the presence of a font file blocks the page-loading process. The time the font file takes to download, parse, and execute delays content rendering. This will slow down the page and affect user experience.

### Flash of Unstyled Text(FOUT) and Flash of Invisible Text(FOIT)

Flash of unstyled text (FOUT) and flash of invisible Text (FOIT) are common issues when using custom web fonts.

FOUT occurs when the browser displays page content in a fallback font before changing it to the custom font. This results in an observable change (or flash) in the text's appearance.

FOIT displays the text in invisible form until the custom fonts finish loading. Both FOUT and FOIT are bad for user experience.

Look at this image from [Malthe Milthers](https://www.malthemilthers.com/font-loading-strategy-acceptable-flash-of-invisible-text/).

![Flash of Unstyled Text and Flash of Invisible Text gif](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image2.gif)

In the above image, before displaying the text in the custom font, 
* FOIT (on the left) shows the text in invisible form.
* FOUT (on the right) shows the fallback font.

For this reason, there is a noticeable delay before getting the preferred custom font.

### Third-party Service Providers

Using third-party custom font services like [Google Fonts](https://fonts.google.com/) (shown in the image below) makes your website's performance dependent on the service.

![Capture](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image3.jpg)


For example, if your service provider experiences downtimes, your font may become unavailable or have a FOIT/FOUT problem.



<CTA_Middle_Basics />


## Web Font Optimization Strategies

The following strategies will help you to optimize the performance of your web fonts:

### Select the Right Font

Choosing the right font for your web project depends on the design goal. Use system fonts or web-safe fonts if performance is the only priority. This will spare you extra optimization efforts, as they require no additional file downloads.

Conversely, If aesthetics and branding also matter besides performance, go with custom fonts.

You can specify web fonts of your choice by declaring them in your CSS like this.

```css
/* Use the @font-face rule to define your custom fonts */
@font-face {
  font-family: 'CustomFont';
  src: url('customfontfilename.woff2') format('woff2'); /* Specifies the font file path and the format */
}

/* Apply your custom font to elements or selectors */
h1 {
  font-family: 'CustomFont';
}

/* For system fonts or web-safe fonts, just apply the font directly */
h1 {
  font-family: Garamond;
}
```

The above code shows that the `@font-face` rule defines your custom font. This allows you to apply it to your HTML elements or CSS selectors. 

Note that you must always wrap your custom font name in single or double ticks, i.e., `'CustomFont'` or `"CustomFont"`, not `CustomFont`.

### Use Font Subsetting

Font subsetting is a technique that involves including only the characters used on a web page in the font file. Doing this reduces the font file size and increases the page load speed.

Tools like [Font Squirrel's Webfont Generator](https://www.fontsquirrel.com/tools/webfont-generator) and [Glyphhanger](https://www.npmjs.com/package/glyphhanger) can automatically generate font subsets. These tools usually work by requesting your original font file, which is then converted to provide a font subset file for your project.

![Font Squirrel's Web Font Generator](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image4.png)

The above image shows how the Font Squirrel's tool works. After uploading your font, select the optimal setting for top speed and performance and download your font.

### Set Fallback fonts

Specifying font fallbacks allows you to decide the font to be displayed if the custom font is not loaded.

Always use web-safe fonts with a style and size similar to your custom font. This helps to maintain the desired appearance even if the custom font is unavailable.

```css
/* Every font after the custom font is a fallback font */
p {
  font-family: 'CustomFont', Arial, sans-serif;
}
```

In the above CSS declaration, if `customFont` does not work, `Arial` will be displayed. If `Arial` also does not work, `serif` takes over. The idea of using a generic family as the last fallback is that it never fails. 


### Preload Fonts

Preloading fonts is an effective strategy to prevent the occurrence of FOUT or FOIT. Using `preload` on a `<link>` tag instructs the browser to treat a font as the top priority and fetch it first in the page load process.

Here's the code to implement it.

```xml
<head>
  <link rel="preload" href="/Fonts/CamingoCode.woff2" as="font" type="font/woff2" crossorigin>
</head>
```
Now, let's do a breakdown of the code.

*  `rel="preload"` instructs the browser to preload the fonts.
*  `href="Fonts/CamingoCode.woff2` specifies the location of the font to be preloaded. In this illustration, the font file, `CamingoCode.woff2`, can be found in the Fonts directory of the web server.
* `as="font"` specifies that the browser should treat the resource to be preloaded as a font.
* `type="font/woff2` helps the browser to understand that the font format is woff2.
* `crossorigin` ensures that your font files are loaded even if they come from a different domain.

### Load Fonts Asynchronously

Loading fonts asynchronously solves the render-blocking problem. With this, the browser will fetch and load font files independently without interfering with rendering the rest of the page.

You can do this using JavaScript and the CSS Font Loading API. This API allows you to control and monitor the loading of web fonts on a web page.

```javascript
// Step 1: Define a FontFace using the font face constructor
const camingoFont = new FontFace("CamingoCode", "url(CamingoCode.woff2)");

// Step 2: Add the FontFace to document.fonts
document.fonts.add(camingoFont);

// Step 3: Load the Font
camingoFont.load();

// Step 4: Wait for the completion of the font loading process
document.camingoFont.ready.then(
  () => {
    // Use the loaded font to render text
  },
  (err) => {
    // To handle the error if font load fails
    console.error("Font loading failed:", err);
  },
);
```

Here's a further breakdown of the code above.

* The `FontFace` object specifies the fonts to be loaded. It takes two parameters: the name and the URL path of the font.
* Adding the `FontFace` object to `document.fonts` signals to the browser that you want to load this font.
*  Adding `load()` to the `FontFace` object explicitly triggers the loading process.
*  `ready` ensures the loading process is complete before implementation. After completing the loading process, `then` uses the loaded font to render the text.
*  The `err` function catches the error if the font loading fails.

### Set Font display to Swap

The `font-display` CSS property specifies how the browser loads and displays custom font files. Setting `font-display` to `swap` ensures that the fallback fonts are displayed until the custom font is available.

```css
@font-face {
  font-family: 'CamingoCode';
  src: url('CamingoCode.woff2') format('woff2'); /* url specifies the location of the font file */
  font-display: swap; /* Controls the browser behaviour during font download */
}
```

The @font-face rule defines a custom font named `CamingoCode` in the CSS code above. The `src` property specifies the `url` location and the font format. Additionally, `font-display: swap` instructs the browser to display a fallback font until `CamingoCode` is available. Implementing this code will improve user experience by minimizing the occurrence of FOUT.

### Compress Custom Font Files

By now, you should know that smaller font files are the best for performance. Compressing fonts reduces the size of font files without compromising their quality.
The following are some of the ways to compress your fonts:

* **Use WOFF2:** The best way to compress your fonts is by converting them to the Web Open Font Format 2 (WOFF2). The WOFF2 is currently the most efficient web font format. It has better compression capabilities than other font formats

* **Use TTF:** Although WOFF2 is widely supported on modern browsers, you might need to use TTF (True Type Font) on some older versions of Internet Explorer. TTF is the second-best alternative to WOFF2. It should be used when WOFF2 is incompatible with a browser.

* **Leverage Tools:** Tools like Font Squirrel's Webfont Generator and [cloudconvert](https://cloudconvert.com/) can convert your font files to WOFF2 and other preferred formats. Follow these steps to use cloudconvert:

* When you reach the homepage, click on select file (as shown in the image below) and choose the font file you want to convert.

![first step](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image5.png)

* Select the format you want the uploaded font to be converted to, and convert the font. 

![second step](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image6.png)

* Download the converted font.

![third step](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image7.png)


### Host Fonts Locally

It is better to host font files locally than on external servers. Hosting your font files on your web server gives you absolute control over their optimization and performance.

This doesn't mean that you shouldn't use third-party services. What you shouldn't do is host your fonts on their servers. Third-party font services usually provide the option to download their fonts for free. For example, although Google Fonts provide hosting for their fonts, there's an option to download and use them for free.



## Tools for Testing Web Fonts Performance

Testing performance is as crucial as optimization. It allows you to assess your optimization efforts and test your web font performance. The following tools will help you in tracking and testing font performance on your website:

### Google PageSpeed Insights

[Google PageSpeed Insights](https://pagespeed.web.dev/) evaluates the user experience of a web page on both mobile and desktop devices. To do this, 

* it conducts a full performance audit on the page,  
* highlights problems discovered, and  
* provides recommendations on how you can improve the page. 

To see how it works, let's use it to diagnose [Nairaland](https://www.nairaland.com/), a popular forum website.
    
![PageSpeed Insights](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image8.png)



The above image shows some opportunities to improve performance. Clicking on them will show you additional information that can be utilized to improve the performance of your page.

For example, clicking on "Eliminating render-blocking resources" shows the following. 

![FONT ISSUE](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image9.png)


The above image specifies the font files blocking the rendering of the page. It also shows the potential time savings of fixing the issue.

### Browser Developer Tools

Your browser developer tools can be a great resource to test the performance of your web fonts. You can utilize it by following these steps:
1. Access the developer tools and go to the Network panel.
2. Check the details of the page's font requests by typing “font” into the filter bar.
3. Alternatively, click on `Font` (underlined green in the image below) to get only font-related requests. 
4. Examine relevant details about each request like `Name`, `Status`, `Size`, and `Time`.

![NewDevTools.png](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image10.png)


If you click on a particular font request (marked blue in the image below), another window opens, which can give you more details on the timing (marked red) of the request. Click on the timing tab to get this information.

![Chrome DevTools Timing](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image11.png)


Even though Chrome DevTools is used for the image samples, the way all this works is similar under Firefox and other browsers.

### WebPageTest

Like PageSpeed insights, [WebPageTest](https://www.webpagetest.org/) evaluates your website. It analyzes load times and rendering, highlighting any bottlenecks present and how you can remove them.

Let's see how it works by analyzing Nairaland.

![webPageTEST](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image12.png)

As shown by the above image, it analyzes the website under three metrics: speed, usability, and resilience.

One of the problems it usually highlights is how fonts affect rendering and load times. It also provides suggestions for solving these problems.

Here's an example of a font-related problem on the analyzed website.
![WebPageTest Diagnosis](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image13.png)

In the above image, the diagnosis shows a problem with loading the fonts. It also suggests a way to solve this problem, i.e., by setting `font-display` to `swap`.

### Google Fonts Checker

Google Fonts is the most popular third-party font service millions of websites use today. It provides an easy way to use different fonts on your page without hosting it on your local web server. However, utilizing multiple Google fonts on a page can affect performance by slowing down page load and affecting user experience.

Google Fonts Checker solves this issue. It scans your website and returns a report on how Google fonts are integrated into your website. It also returns any performance issues discovered. This way, developers enjoy the versatility of Google fonts without sacrificing performance.

Several free online tools that can help you analyze your Google fonts. A good example is the [CCM19](https://www.ccm19.de/en/google-fonts-checker/) Google Fonts Checker.

Again, let's analyze Nairaland to see how it works.

![ccm19](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image14.png)

The left side of the above image specifies the font issues on the website. Furthermore, clicking the “To the details” link takes you to a page giving more information on the issues as shown below, as shown below.

![results](https://blog.openreplay.com/images/definitive-guide-to-web-fonts-optimization/images/image15.png)

## Conclusion

And that's a wrap. We have examined web fonts from a performance perspective. We learned about the types of web fonts, their performance challenges, their optimization strategies, and the tools for testing their performance.

In web development, many things change. However, the desire for beautiful typography and fast web pages remains the same. For this reason, web font optimization should not be seen as a one-off process. It should rather be seen as an iterative approach to making our websites attractive without sacrificing performance.