FontSpider:字蛛中文字体压缩器是一个可以让网页自由引入中文字体的源码工具,通过分析本地 CSS 与 HTML 文件获取 WebFont 中没有使用的字符,并将这些字符数据从字体中删除以实现压缩,同时生成跨浏览器使用的格式。
官网:http://font-spider.org/
特性
- 轻巧:数 MB 的中文字体可被压成几十 KB
- 简单:完全基于 CSS,无需 js 与服务端支持
- 兼容:自动转码,支持 IE 与标准化的浏览器
- 自然:文本支持选中、搜索、翻译、朗读、缩放
原理
字蛛通过分析本地 CSS 与 HTML 文件获取 WebFont 中没有使用的字符,并将这些字符数据从字体中删除以实现压缩,并生成跨浏览器使用的格式。
- 构建 CSS 语法树,分析字体与选择器规则
- 使用包含 WebFont 的 CSS 选择器索引站点的文本
- 匹配字体的字符数据,剔除无用的字符
- 编码成跨浏览器使用的字体格式
安装
安装好 nodejs,然后执行:
[html]pm install font-spider -g
[/html]
- windows 需要安装 perl 环境才可以运行。
- GruntJS 用户可使用 gruntjs 插件。
使用范例
在 CSS 中声明字体
[css]/*声明 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’;
}
[/css]
@font-face
中的src
定义的 .ttf 文件必须存在,其余的格式将由工具自动生成- 不支持动态插入的 CSS 规则与字符
- 不支持 CSS
content
属性插入的字符
压缩 WebFont
[html]font-spider [options] <htmlFile …>
[/html]
支持通配符,例如:
font-spider dest/*.html
Options
[js]-h, –help 输出帮助信息
-V, –version 输出当前版本号
–info 仅提取 WebFont 信息显示,不压缩与转码
–ignore <pattern> 忽略的文件配置(可以是字体、CSS、HTML)
–map <remotePath,localPath> 映射 CSS 内部 HTTP 路径到本地
–debug 开启调试模式
–no-backup 关闭字体备份功能
–silent 不显示非关键错误
–revert 恢复被压缩的 WebFont
[/js]
字体兼容性参考
格式 | IE | Firefox | Chrome | Safari | Opera | iOS Safari | Android Browser | Chrome for Android |
---|---|---|---|---|---|---|---|---|
.eot |
6 | — | — | — | — | — | — | — |
.woff |
9 | 3.6 | 5 | 5.1 | 11.1 | 5.1 | 4.4 | 36 |
.ttf |
— | 3.5 | 4 | 3.1 | 10.1 | 4.3 | 2.2 | 36 |
.svg |
— | — | 4 | 3.2 | 9.6 | 3.2 | 3 | 36 |