Daily development of web pages often use some special fonts, such as the source of bold, apple font, etc., because these fonts do not exist in the general host environment, need to pass the CSS @font-face definition, and load the corresponding font file from the server, and the font file is generally relatively large, Even sometimes a font is bigger than all the other resources (JS, CSS, images) combined, and has a very critical impact on the loading performance of web pages, so it is necessary to optimize the font. This article mainly from the font format, extraction on demand, unified rendering three aspects to talk about the common techniques of optimizing fonts.

Convert font format

Here we are in 1202, and wOFF2 is supported on almost every major device, so there is no need to include a variety of different fonts on your website. In general, it’s recommended to just introduce Woff2 to keep the code simple and reduce the number of files uploaded to your server. Why not?

However, most of the time, art students only provide us with font files in other formats, such as TTF or OTF. How to convert them to WOFF2?

  • TTF font to WOFF2

The TTF font is supported by both Apple and Windows, so it is a favorite among art students. TTF conversion WOFF2 is relatively simple, you can choose to convert online, recommended sites have the following two

  • ttf-to-woff2
  • webfont-generator

But personally, I prefer to use node library TTf2Woff2 because online conversion takes a long time to upload and sometimes generates blank files. With more than 10W downloads per week, many people will want to convert TFF to WOFF2. It’s also easy to use:

cat font.ttf | ttf2woff2 > font.woff2
Copy the code

Since the cat command is used to extract the TTF contents, if you are using Windows, you will need to use Git bash or WSL to run it.

  • Turn OTF WOFF2

In addition to TTF, art students also often provide us with OTF, which is a font jointly developed by Microsoft and Adobe, so it is relatively popular in Windows platform. So how do you convert it to WOFF2? So far I haven’t found any online sites or Node libraries that can be converted in one step. A Google search for several online conversion sites will either fail to download after the conversion, or the file will be empty after the conversion.

After some trouble, found a good Python library OTF2TTF, can be stable otF to TTF. Otf2ttf is a python package manager that can be installed using PIP (PIP is similar to NPM, it is a package manager for Python), but there is a small error in the official documentation of the sample code:

otf2ttf MyFont.ttf
Copy the code

MyFont. TTF should be MyFont. Otf because the input should be otF not TTF.

After generating the TTF file with Python otf2ttf, you can get woff2 using the method mentioned above to convert TTF to Woff2.

This is not a single font, but a package of multiple fonts. You need to extract the TTF from it before you can use it. Try using TTC2TTF.

Compress fonts as needed

Generally, even if the font is converted to Woff2 format, the minimum is still in the hundreds of K, and more often in the 1-4M range. Sometimes only a few characters need a special font. For example, if only the 10 numbers 0 to 9 need a special font, it is unnecessary to import the entire font file, which is larger than cutting 10 images. Fortunately, there are some techniques that can extract a subset of fonts that correspond to the numbers 0-9. Font = “spider” > < p style = “margin-bottom: 0pt;

First, install the background-spider globally:

npm install font-spider -g
Copy the code

Then, create a new HTML file, such as index.html, with an element containing all the text you want to extract, such as 0-9, and define the special font you want for that element:

 <h1>0123456789</h1>


<style>
@font-face {
  font-family: 'sourceHan';
  src: url('./SourceHanSansCN-Regular.ttf');
  font-weight: normal;
  font-style: normal;
}


h1 {
    font-family: 'sourceHan';
}
</style>
Copy the code

Finally, run the following command in the directory where the HTML file is located:

font-spider index.html
Copy the code

At this point, the original sourcehansanscn-regular.ttf will be moved to the.font-spider/ directory, and the font in the original location will be replaced with a font file that extracts only 0-9 fonts. This volume is off by several orders of magnitude:

The full font file size is 10M:

Extract only 0-9 10 digit font files with only 7K:

So, if your site content is static, it is recommended to use a font spider to extract the text you need. This will greatly reduce the size of the font file.

Uniform render timing

Convert fonts to WOFF2 and static content web sites using a font spider for on-demand compression, giving you good control over font size. (PS: There is no need to open GZIP for WOFF2 because the text itself is compressed).

Finally, let’s take a look at the effect of network speed on font content. If you use a font for all of your web pages, CSS is defined as follows:

@font-face {
  font-family: myfont;
  src: url('./myfont.woff2') format('woff2');
}


body {
  font-family: myfont;
}
Copy the code

If the myfont. Woff2 file size is 4M and the network download speed is only 1M/s, it will take 4 seconds to load the font. What font will the browser render with during the 4 seconds since the remote font has not been loaded yet? In fact, different browsers will behave differently. Here are some common desktop browsers:

  • IE: It will render directly with the spare font and then wait for the WebFont to load.

  • Safari: It waits for the WebFont to finish loading and does not render the font.

  • Chrome/Firefox: They wait for the WebFont font to load, and if it doesn’t do so within 3 seconds, use the alternate font rendering. Finally, the WebFont is loaded, used and rerendered.

We need to find a way to unify these behaviors. The ideal behavior is to use the system default font first and then replace it with a special font after the remote font has loaded. This effect can be easily achieved by using WebFontLoader. Here’s how to use it:

  1. Define a font in CSS with @font-face:
@font-face {
  font-family: 'myfont';
  src: url('./myfont.woff2') format('woff2');
}
Copy the code

Note that you only need to define the font in CSS, not use this word.

  1. Then introduce the WebFontLoader (which can also be installed via NPM) to add the font names you defined in your CSS tocustom.familiesList, and add the font to the corresponding element in the active callback as follows:
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<script>
WebFont.load({
  custom: {
    families: ['myfont'],},classesfalse.active() {
    document.body.style.fontFamily = 'myfont'; }});</script>
Copy the code

The browser will render the content with the default font at first, and then re-render it with the special font when the font is loaded.

summary

About the font optimization skills to write here, there are questions welcome to leave a message exchange ha.