Using font spider to compress web font

Time:2020-3-28

Original link: use font spider to compress web font

With the rapid development of web technology, the content of web interface becomes more and more rich and dazzling, including various custom fonts in web pages.

For example, the front page font of a personal blog:

Using font spider to compress web font

CSS3 introduced@font-face This property can solve this problem well and help us to use some special fonts very flexibly. Even if the font is not installed in the user’s computer, the web page can be displayed.

EOTFont is the preferred format of IE browser, which is not supported by other browsers; other browsers prefer commonTTFSVGWOFF

The basic syntax is as follows:

@font-face {
    Font family: < user defined name of a font >;
    SRC: URL ('< downloaded font, path saved in the computer >');
    font-variant: <font-variant>; 
    font-stretch: <font-stretch>;
    font-style: <style>;
    font-weight: <weight>;

For example:

@font-face {
    font-family: 'Lora';
    src: url('../fonts/STKaiti.eot'); /* IE9 Compat Modes */
    src: url('../fonts/STKaiti.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
           url('../fonts/STKaiti.woff2') format('woff2'), /* Super Modern Browsers */
           url('../fonts/STKaiti.woff') format('woff'), /* Modern Browsers */
           url('../fonts/STKaiti.ttf') format('truetype'), /* Safari, Android, iOS */
           url('../fonts/STKaiti.svg#STKaiti') format('svg'); /* Legacy iOS */
    font-style: normal;
    font-weight: normal;
}

body {
  font-family: STKaiti;
  ...
}

Test effect: chrome, Firefox, ie7-ie11 can achieve

Using font spider to compress web font

1. Font problems

Although the custom Chinese font is cool, there is a drawback, that is, the Chinese font is too large, which is very resource-consuming. The specific reason is actually very simple: English only has 26 letters, and 128 character sets on an ASCII code table can almost represent any English statement. Because of the small character set, font files can also be very small; Chinese fonts are totally different, justGB2313The number of Chinese characters (including symbols) is 7445, and the number of characters isASCII58 times of the code table, and the font designer needs to design the font for each Chinese character. With simple calculation, the size of the Chinese font file is almost dozens of times of the English font file.

2. Solutions

In fact, the solution is very simple. Only keep the text in the page in the font library, delete a large number of other unused text, and generate a small font file containing only specific characters, which can greatly reduce the font file, thus improving the access speed. Now that we have ideas, are there ready-made tools?

3. Cutting tools

Using font spider to compress web font

Really. After my search, I found two tools: one is the Chinese developed “word spider”, the English namefont-spider, which depends on the node.js environment, is a command-line tool. The main idea is to collect fonts used in online web pages, separate them from font files, and complete large-scale compression. The other is Tencent’s new version of font soider, called font spider plus. They work as follows:

Using font spider to compress web font

I choose to use font spider plus. After all, the revised version has fewer bugs and more functions. It also supports online dynamic rendering of pages. The only problem is that the official documents are so vague that many people don’t know how to use them. I’ll give you a detailed example of how to use font spider plus.

4. How to use font spider plus

According to the official documents, to use font spider plus, you need toCSSPassed in file@font-faceIntroduce full size special fonts. How to do it? No, I’ll tell you.

Write HTML file

First, we create a new folder to put HTML files:

$ mkdir index

Then create aindex.htmlThe contents of the document are as follows:

<div class="test">
Michelangelo
</div>
<style>
  @font-face {
    font-family: 'font';
    src: url('../fonts/<font>.eot');
    src:
      url('../fonts/<font>.eot?#font-spider') format('embedded-opentype'),
      url('../fonts/<font>.woff2') format('woff2'),
      url('../fonts/<font>.woff') format('woff'),
      url('../fonts/<font>.ttf') format('truetype'),
      url('../fonts/<font>.svg') format('svg');
    font-weight: normal;
    font-style: normal;
  }
  .test{
      font-family: 'font';
  }
</style>
  • Please send<div class="test"> </div>Replace the text in with the text in your own website. You can choose to select all the articles in your blog and paste them here.
  • Download the font you want to use tofontsFolder, and then in index.html<font>Change to the prefix of the font you downloaded.

Special note:@font-faceMediumsrcThe defined. TTF file must exist and the rest of the format will be generated automatically by the tool

The following is the English name corresponding to the Chinese font:

New thin body: pmingliu 
Minutiae: Mingliu 
Script: dfkai sb 
Bold: simhei 
Tahoma: Simsun 
New Tahoma: nsimsun 
Fangsong: Fangsong 
Kaiti 
Fangsong GB2312: Fangsong GB2312 
Kai Ti GB2312 
Microsoft bold: Microsoft JhengHei 
Microsoft YaHei 

Some fonts will be added when installing office: 
Official script: Lisu 
Youyuan 
Chinese light black: stxihei 
Chinese script: stkaiti 
Chinese Tahoma: stsong 
Chinese song: stzhongsong 
St Fangsong in Chinese 
Founder shutI: fzshuti 
Founder Yao Ti: fzyaoti 
Chinese color cloud: stcaiyun 
Chinese amber: sthupo 
Chinese official script: stliti 
Chinese Xingkai: stxingkai 
Chinese New Wei: stxinwei 

Fonts in Apple: 
Chinese light black: stheiti light [stxihei] 
Chinese bold: stheiti 
Chinese script: stkaiti 
Chinese Tahoma: stsong 
St Fangsong in Chinese 
Lihei Pro: lihei Pro Medium 
Lisong Pro Light 
Script: biaukai 
Apple ligothic medium 
Apple lisung light

Compress local webfont

Then execute the following command to compress the local webfont:

$ fsp local index/index.html

Oh, by the way, you need to install the FSP command through NPM first:

$ npm i font-spider-plus -g

After compression, the compressed font file will be generated in the fonts Directory:

$ ll fonts/

total 41328
-rw-rw-rw-  1 cnsgyg  staff   7.7K 11 21 01:08 STKaiti.eot
-rw-rw-rw-  1 cnsgyg  staff   8.2K 11 21 01:08 STKaiti.svg
-rw-rw-rw-  1 cnsgyg  staff   7.6K 11 21 01:08 STKaiti.ttf
-rw-rw-rw-  1 cnsgyg  staff   7.7K 11 21 01:08 STKaiti.woff
-rw-rw-rw-  1 cnsgyg  staff   3.9K 11 21 01:08 STKaiti.woff2

Font files before compression will be moved tofontsDirectory.font-spiderCatalog:

$ ll fonts/.font-spider

total 24880
-rw-rw-rw-  1 cnsgyg  staff    12M 11 21 01:08 STKaiti.ttf

Writing CSS

Now that the font is compressed, how can I apply it to my website? Also very simple, write a CSS first@font-faxeThe format of the compressed font is similar to the index.html in the first step:

/* fonts-zh.css */
@font-face {
  font-family: 'font';
  src: url('../fonts/<font>.eot');
  src: url('../fonts/<font>.eot?#font-spider') format('embedded-opentype'),
         url('../fonts/<font>.woff2') format('woff2'),
         url('../fonts/<font>.woff') format('woff'),
         url('../fonts/<font>.ttf') format('truetype'),
         url('../fonts/<font>.svg') format('svg');
  font-weight: normal;
  font-style: normal;
  }

This is not good. You need to copy the compressed font files to your website. You need to find these font files through the relative path in CSS. But I don’t want to do it. It’s too much trouble. I want to be simpler.

Base64 encoding

Brainstorm, think of Base64, after coding, you can not copy these font files, but also reduce the loading volume of the website font, which is really a double shot! I won’t explain the specific steps, just put all the steps into the script:

#!/bin/bash

font=STKaiti

eot=$(cat fonts/$font.eot|base64|tr -d '\n')
woff=$(cat fonts/$font.woff|base64|tr -d '\n')
woff2=$(cat fonts/$font.woff2|base64|tr -d '\n')
ttf=$(cat fonts/$font.ttf|base64|tr -d '\n')
svg=$(cat fonts/$font.svg|base64|tr -d '\n')

cat > fonts-zh.css <<EOF
@font-face {
    font-family: '$font';
    src: url(data:application/font-eot;charset=utf-8;base64,$eot) format('eot');
    font-weight: normal;
    font-style: normal;
}
@font-face {
    font-family: '$font';
    src: url(data:application/font-woff2;charset=utf-8;base64,$woff2) format('woff2'),
         url(data:application/font-woff;charset=utf-8;base64,$woff) format('woff'),
     url(data:application/font-ttf;charset=utf-8;base64,$ttf) format('truetype'),
     url(data:application/font-svg;charset=utf-8;base64,$svg) format('svg');
    font-weight: normal;
    font-style: normal;
}
EOF

After executing the above script, afonts-zh.css, this is the only thing we need, no more additional documents.

Introducing CSS

The last step is to introduce this CSS into your website. The specific approach is similar and slightly different. Take Hugo for example, firstfonts-zh.cssCopy tostatic/css/Directory, and then<head></head>The CSS is introduced into the topic of beatiful Hugo, and thelayouts/partials/head_custom.htmlAdd the following line:

<link rel="stylesheet" href="{{ "css/fonts-zh.css" | absURL }}" />

Finally, let the body of the website use the Chinese font. The specific method is to modify the CSS of the body. Take Hugo’s beautiful Hugo theme as an example, modifystatic/css/main.cssBody property in:

body {
  font-family: STKaiti;
  ...
}

You can add alternate fonts, such as:

body {
  font-family: STKaiti,Cambria;
  ...
}

Indicate ifSTKaitiFont not available, will useCambriaTypeface. It’s finished here. For specific effects, please refer to my website: https://fuckcloud native.io/.

5. summary

If you don’t have obsessive-compulsive disorder, it will be a success at this stage, but I don’t think it’s simple enough. So many steps are too tedious. I want to make them all automated and put all the steps into an automated script. It’s not enough. In order to benefit the public, I built a new warehouse in GitHub, where all the scripts and steps are on it, and the small partners with needs can take them to happy~~

Project address: https://github.com/yangchuansheng/font-spider-plus

6. References

  • How to use Chinese fonts gracefully in web pages
  • Font spider makes you fall in love with @ font face web page custom font

WeChat official account

Sweep the following two-dimensional code, pay attention to WeChat official account, reply to the official account and join the group of cloud native communication, discuss with cloud, Sun Hongliang, Zhang Guanchang, Yangming and other big guys together.

Using font spider to compress web font