likes
comments
collection
share

字体包体积优化,提高网页加载速度!

作者站长头像
站长
· 阅读数 2

简述

当页面加载过多的字体文件时,由于字体包的体积过大,会产生页面加载过慢的问题。

font-spider(字蛛)是一个智能 WebFont 压缩工具,它能自动分析出页面使用的 WebFont 并进行按需压缩。以减小字体包的体积。

font-spider有如下特性:

1.压缩字体:智能删除没有被使用的字形数据,大幅度减少字体体积
2.生成字体:支持 woff2、woff、eot、svg 字体格式生成

安装

因为font-spider不是频繁用到的工具,所以使用局部安装。

  1. 新建文件夹spider

  2. 初始化package.json

npm init -y
  1. 安装:
npm install font-spider

使用

  1. spider目录下新建index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>font-spider</title>
    <style>
      @font-face {
        font-family: 'source'; /* 名字自己定义就好 */ 
        /* ttf 字体必须存在,否则会报错 */
        src: url('./font/source.ttf') format('truetype');  
        font-weight: normal;
        font-style: normal;
      }
    
      /* 若使用以下配置,支持生成其他格式的字体 */
      @font-face {
        font-family: 'source';
        src: url('./font/source.eot');
        src:
          url('./font/source.eot?#font-spider') format('embedded-opentype'),
          url('./font/source.woff2') format('woff2'),
          url('./font/source.woff') format('woff'),
          /* ttf 字体必须存在,否则会报错 */
          url('./font/source.ttf') format('truetype'),
          url('./font/source.svg') format('svg');
        font-weight: normal;
        font-style: normal;
      }
      
     /* @font-face 可以支持多个 */
    </style>
  </head>
  <body>
    <!-- font-family 与上的对应,如果不写这个文案,应该是默认常用字体 -->
    <div style="font-family: source">
        <!-- 这里面写入需要用到字体的文案 -->
    </div>
  </body>
</html>
  1. 将对应的字体放到对应的文件夹下

  2. 执行以下代码:

// 语法
npx font-spider [options] <htmlFile1 htmlFile2 ...>

// 使用
npx font-spider index.html

执行成功后,font 文件夹中会出现一个.font-spider文件夹,里面的是未压缩的文件,font目录下的字体会被相应的替换,为被压缩后的字体,并且会生成多种格式的字体。

参考文档

官方地址:

// 官网(可能需要翻墙)
http://font-spider.org
// github 地址
https://github.com/aui/font-spider/blob/master