使用工具缩小字体文件的体积
npm install font-spider -g
页面中
/*声明 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';
}
生成
font-spider ./demo/*.html
- 这种方法需要在htm中引用ttf文件,然后由工具探测htm中的文字和ttf路径
- 将文字和ttf文件对比,生成只保留了htm中文字的ttf文件
- 这种方法可以有效降低字体文件体积,提高访问速度
- 网页内的文字经常变的话,一旦超出了ttf包含的文字范围,就需要重新生成字体文件,否则字体显示就会出问题,所以只适合网页内容长期固定的站点
- 由于工具并不是特别智能,只支持简单的html站点,碰到复杂的站点,就无法正常生成
- 工具依赖于特定的网站结构,所以使用起来并不是很方便
通过js进行预加载
css
@font-face {
font-family: ft; /*这里是说明调用来的字体名字*/
src: url('font.TTF') format('truetype'); /*这里是字体文件路径*/
}
* {
font-family: STSong;
}
.myFont {
font-family: ft !important; /*这里设置某参数的字体值,在这里调用了你刚才声明的字体值"fz"*/
}
js
$(function () {
//载入css文件
$("<link>")
.attr({
rel: "stylesheet",
type: "text/css",
href: "/css_js/FontFamily/customFont.css",
onload: ""
})
.appendTo("head");
//载入自定义字体预加载模块
$("<df>")
.attr({
class: "myFont",
style: 'color:rgba(1,1,1,0)'
}).html(0)
.appendTo("body");//模块里必须有字符,否则字体不会加载
})
//加载完成之后更换页面字体
$(window).load(function () {
$("<style>").html(
'*{font-family: ft !important; }'
).appendTo("head");
})
- 可以使字体文件在后台加载,而不影响原本页面的显示
- 在字体文件加载完成之后,自动更新字体
- 这种方式比较灵活,可以放在任意页面里
- 虽然不干扰正常的显示,但是仍然要等字体文件加载完成才能使自定义字体生效
- 比压缩字体的方式简单点