Front-end web font optimization guide

Front-end web font optimization guide

  • Daily development of web pages often uses some special fonts, such as Siyuan HeiTi, Pingfang fonts, etc., because these fonts do not exist in the general host environment, they need to be defined by @font-face of css, and the corresponding fonts are loaded from the server Font files, and font files are generally relatively large, and sometimes even a font is larger than all other resources (js, css, pictures) combined, which has a very critical impact on the loading performance of web pages, so there are Some optimization of fonts is necessary. This article mainly talks about common techniques for optimizing fonts from three aspects: font format, on-demand extraction, and unified rendering.

Convert font format

It is now 2023, and all mainstream devices basically support the woff2 font format, so there is no need to introduce multiple fonts in different formats into the website. Generally, it is recommended to only import woff2, which can keep the code concise and reduce the files uploaded to your server. Why not?
But many times, art students only provide us with font files in other formats, such as TTF or OTF, so how to convert them into woff2?

TTF font to WOFF2

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

  • However, I personally feel that the online conversion takes a long time to wait for the upload, and sometimes the generated file is blank, so I prefer to use the node library ttf2woff2 for conversion. The weekly download volume of this library has reached 100,000+, which shows that many people will have the need to convert tff to woff2. The method of use is also very simple:

cat font.ttf | ttf2woff2 > font.woff2
  • Because the cat command is used to extract the contents of ttf, if you are using windows, you need to use git bash or wsl to run.

OTF to WOFF2

  • In addition to TTF, art students often provide us with OTF, which is a font jointly developed by Microsoft and Adobe, so it is still relatively popular on the Windows platform. So how to convert it to WOFF2? At present, I have not found any online website or node library that can be converted in one step. I searched for several online conversion websites on Google. Either the conversion cannot be downloaded after the conversion is completed, or the converted download is an empty file. Anyway, it is unreliable. s things.
  • After some tossing, I found a good python library otf2ttf, which can stably convert otf to ttf. The method of use is also relatively simple. First install python, and then install otf2ttf through pip to use it (pip is similar to npm, which is a package manager for python), but there should be a small typo in the sample code in the official document:
otf2ttf MyFont.ttf
  • Inside MyFont.ttf should be MyFont.otf, because this input should be OTF type instead of TTF.

  • After using python otf2ttf to generate the ttf file, you can use the method of converting ttf to woff2 mentioned above to get woff2.

    Let’s talk about font conversion here: Sometimes art students will provide us with ttc files. This is not a single font, but a package of multiple fonts. You need to extract ttf from it before you can use it. You can try TTC2TTF .

Compress fonts on demand

  • Generally, even if the font is converted into woff2 format, the minimum size is still hundreds of K, and in more cases, it will be about 1-4M. Sometimes, we only need to use a special font for a few texts, for example, only 10 numbers from 0-9 use a special font. If you import the entire font file, it is unnecessary, which is bigger than cutting 10 pictures . Fortunately, there are some technologies that can extract the font subsets corresponding to the 10 numbers 0-9. I usually use font-spider to extract.
  • First, install font-spider globally:
npm install font-spider -g
  • Then, create a new html file, for example, the file name is index.html, and use an element to contain all the text you want to extract, such as 0-9, and define the special font you want for this 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>
  • Finally, execute the following command in the directory where the html file is located:
font-spider index.html
  • At this time, 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 only extracts 0-9. This volume differs by several orders of magnitude:

  • The full font file size is 10M:

  • A font file that only extracts numbers 0-910 is only 7K:

  • Therefore, if your website content is static and unchanged, it is recommended to use font-spider to extract the text you want to use, which will greatly reduce the size of font files.

Unified rendering timing

  • Convert fonts to WOFF2 and use font-spider for on-demand compression on static content websites, which can control the size of fonts well. (PS: It is not necessary to enable GZIP for the WOFF2 font, because the text itself is compressed).
  • Finally, let's take a look at the impact of network speed on font content. If your webpage uses a certain font for all content, the CSS definition is as follows:
@font-face {
    
    
  font-family: myfont;
  src: url('./myfont.woff2') format('woff2');
}


body {
    
    
  font-family: myfont;
}
  • If the size of the myfont.woff2 file is 4M, and the network download speed is only 1M/s, it will take 4 seconds to load this font. During these 4 seconds, since the remote font has not been loaded yet, what font will the browser use for rendering? In fact, different browsers behave differently. Here are some common desktop browsers:
    • IE: It will directly use the alternate font rendering, and finally re-render after the webfont font is loaded.
    • Safari: It waits for the webfont font to load, and does not render the font during this time.
    • Chrome/Firefox: They wait for the webfont to load, and if it doesn't load within 3 seconds, render with an alternate font. Finally the webfont is loaded, used and re-rendered.
  • We need to find a way to unify these behaviors. The ideal behavior is: first use the system default font, and then replace it with a special font after the remote font is loaded. This effect can be easily achieved with the help of WebFontLoader . Let's see how to use it:

Define a font in css via @font-face:

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

Note that you only need to define the font in CSS, instead of using this word.

  • Then import webfontloader (can also be installed through npm), add the font name you defined in css to the custom.families list, and add the font to the corresponding element in the active callback, the code is as follows:
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
<script>
WebFont.load({
      
      
  custom: {
      
      
    families: ['myfont'],
  },
  classes: false,
  active() {
      
      
    document.body.style.fontFamily = 'myfont';
  },
});
</script>
  • In this way, the browser will use the default font to render the content at the beginning, and then re-render with the special font after the font is loaded.

Guess you like

Origin blog.csdn.net/weixin_44733660/article/details/130326276