Home / Notes /

Reduce Font Loading Time in My Blog

I use Source Han Serif on my blogs. And it takes ages to load. Source Serif Pro Regular (an English font) has a size of 217 KB. Source Han Serif Regular? 23.6 MB. I have to reduce the size of the font file!

Woff2 is said to be a compressed format. Here is the girhub repo.

      $ git clone --recursive https://github.com/google/woff2.git --depth 1
$ cd woff2
$ make clean all
$ ./woff2_compress /Users/yuan/p/casouri/misc/SourceHanSerifSC-Regular.otf
Processing /Users/yuan/p/casouri/misc/SourceHanSerifSC-Regular.otf =>
Compressed 23613247 to 15551008.

After converting to woff2 format, the size is reduce to 15.6MB, still too large.

Source Han Serif covers a lot of rare glyph. Maybe cutting them out can give me a smaller file. fonttool has s subcommand pyftsubset that produces a subset of a font file.

      pyftsubset ~/p/casouri/misc/SourceHanSerifSC-Regular.otf \
           --unicode=0-7f, 3000-303f,4e00-9faf --flavor=woff2

gives a font file with only ASCII, CJK Unified Ideographs and CJK Symbols and Punctuation, compressed to woff2 format. The reduced size is 10.9 MB. Still not good.

I need even less glyph in my font file. For that I find a file with 3500 most used Chinese glyph in it, and pass that to pyftsubset. (you can find the file at here.)

      pyftsubset ~/p/casouri/misc/SourceHanSerifSC-Regular.otf \
           --unicodes=0-7f,3000-303f \

This cuts down the size to 1.7 MB. That’s still large comparing to English fonts, but I’m happy with it.

No, not really, it’s still slow, but at least it’s faster than before… If I want it to load even faster than that, I need to generate font files that only contains the glyph of a particular page. That’s not trivial for a static site.

(Update <2019-07-22 Mon 14:20>)

Since the Chinese fonts still takes a while to load even with the compressed size. It is best to display a default system font before the web font is loaded so the user won’t stare at empty spaces. This is done by font-display property. font-display: swap will display default font almost immediately and swap to web font one it is loaded.

(Update <2021-04-20 Tue 22:54>)

The previous font I created has some problems, it doesn’t contain punctuation marks and misses some common glyphs. I fixed those issues and the new file is at here. I don’t want the font file to contain Latin characters, so that Latin characters can fall back to my English font. So I also changed the command:

      pyftsubset ~/p/casouri/misc/SourceHanSerifCN-Regular.otf \
           --text-file=常用字及符号.txt \

Written by Yuan Fu

First Published in 2019-07-15 Mon 21:28

Last modified in 2021-04-20 Tue 23:15

Send your comment to [email protected]