使用font-spider[字蛛]对ttf文件进行压缩
原理:
字蛛通过分析本地 CSS 与 HTML 文件获取 WebFont 中没有使用的字符,并将这些字符数据从字体中删除以实现压缩,同时生成跨浏览器使用的格式。
font-spirder 官网:http://font-spider.org/
第一步:先安装好 NodeJS,然后执行:
npm install font-spider -g
第二步:在CSS中使用WebFont:
/*声明 WebFont*/
@font-face {
font-family: 'pinghei';
src: url('../font/pinghei.eot');
src:
url('../font/pinghei.eot?#font-spider') format('embedded-opentype'),
url('../font/pinghei.woff') format('woff'),
url('../font/pinghei.ttf') format('truetype'),
url('../font/pinghei.svg') format('svg');
font-weight: normal;
font-style: normal;
}
/*使用选择器指定字体*/
.home h1, .demo > .test {
font-family: 'pinghei';
}
1. @font-face 中的 src 定义的 .ttf 文件必须存在,其余的格式将由工具自动生成
2. 开发阶段请使用相对路径的 CSS 与 WebFont
第三步:运行font-spider命令:
font-spider ./demo/*.html
页面依赖的字体将会自动压缩好,原 .ttf 字体会备份。
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
使用结果如下:
1、使用BootStrap的 Glyphicons Halflings ,由45KB 压缩至 2KB,而且生成.eot等文件;
而自己加载的苹方字体原来11M,压缩后还是11M,未被压缩,也未生成.eot等文件,效果并不理想。
2、文件夹中多了一个存放压缩前字体的 font-spider文件夹,对原字体进行了备份。