title = "Optimise loading times with a custom font subset"
date = 2023-04-29
description = "Learn how to create a custom subset that only includes the necessary glyphs."
[taxonomies]
tags = ["showcase", "tutorial"]
+++
## The problem
Custom fonts cause flashing text in Firefox. For a gif and more details, see [this issue](https://github.com/welpo/tabi/issues/75).
## The solution
To fix this, tabi loads a subset of glyphs for the header. Since this (slightly) increases the initial load time, it's a good idea to try and minimise the size of this subset.
By default, there are subset files for English and Spanish characters (with a few symbols). These files are loaded when the Zola page/site is set to that language.
For further optimisation, you can create a custom font subset that only includes the characters used in your header.
Run `pip install fonttools brotli` to install both.
## The script
The script below takes a `config.toml` file and a font file as input, extracts the necessary characters, creates a subset of the font, and generates a CSS file containing the base64 encoded subset.
You should place this `custom_subset.css` file inside the `static/` directory.
## Automating with Pre-commit Hook
You might change the title or menu options of your site, making the custom subset no longer useful.
To automate the process of creating this file, you can integrate the script into a Git pre-commit hook that checks for changes in the `config.toml` file, runs the script, and stores the resulting CSS file in the `static/` directory of your site.
1. Create a `.git/hooks/pre-commit` file in your Git project, if it doesn't already exist.
2. Make it executable with `chmod +x .git/hooks/pre-commit`.
3. Add the following code to the file:
```bash
# Check if config.toml has been modified.
if git diff --cached --name-only | grep -q "config.toml"; then
# Add the generated subset.css file to the commit.
git add static/custom_subset.css
fi
```
Make sure to modify the script to match the path where you stored the `subset_font` script. The config and font paths should work fine with tabi's default setup.
Now, every time you commit changes to your Git project, the pre-commit hook will check for modifications in the `config.toml` file and automatically run the `subset_font` script to update the `custom_subset.css` file.
By the way, if you're interested in a way to automatically update the date of your Zola posts or compress your PNG files, check out [this post](https://welpo.ooo/blog/zola-date-git-hook/).
If you want to use all scripts at once (compressing PNG files, updating the date, and creating the font subset), combine their code into a single `.git/hooks/pre-commit` file.