Font-spider
字蛛是个中文字体压缩器。简单来说就是检测网页上用到了哪些字,然后把原字体文件中没用到的字删掉,使得在压缩字体文件大小的同时也不影响网站的正常显示。对于静态部署的博客来说不失为一种提高网页加载速度的好方案。
先用npm安装下载。
npm install font-spider -g
我的思路是遍历所有博文,收集起来丢进集合,然后输出一个包含网站所有文字的网页提供给字蛛。
鉴于博文主要都在_posts
文件夹内,我就没爬其他page页面了。理论上该爬的,但post本身文本量够大,我就偷了个懒。
# coding:utf-8
import os
postPath = 'E:/Recent/MyBlog/source/_posts' # _posts文件夹位置
path = os.path.dirname(__file__) # 所在文件夹位置
def getFile(logPath):
text = ""
for file in os.listdir(logPath):
fileInput = os.path.join(logPath,file)
with open(fileInput,'r',encoding="utf-8")as fi:
text += fi.read()
return set(text) # 返回一个包含所有post文字的集合
content = "".join(getFile(postPath)) # set转str
title = "<meta charset=\"UTF-8\">\n<link rel=\"stylesheet\" href=\"word.css\">\n<body>\n"
content = title + content +"\n</body>" # 网页内容
fileOutput = os.path.join(path,"word.html")
with open(fileOutput,'w',encoding="utf-8")as fo:
fo.write(content) # 输出html文件
print("Words are collected.\n") # 一个回应
在同文件夹下放了字体文件和样式文件(word.css
)。
@font-face{
font-family:"CH";
src:url(../H-TTF-BuMing-R-2.ttf);
}
body{
font-family:"CH"
}
最后一个简单的脚本。
@echo off
python word.py
Xcopy E:\Recent\MyBlog\themes\hexo-theme-white-master\source\font\.font-spider\H-TTF-BuMing-R-2.ttf E:\Recent\MyBlog\themes\hexo-theme-white-master\source\font /Y
font-spider word.html
这里这样写主要是因为运行font-spider之后,它会在原字体文件目录下新建.font-spider
文件夹,把该字体文件备份过去;然后把原字体文件替换为压缩过的新字体文件。
如此,我使用的「不明体」可以直接从12MB压缩到1.1MB。