使用font-spider实现按需加载字体

栏目: NodeJs 发布时间:2022-02-09

在项目开发中,UI 团队为数字指定了专用字体,大家都知道在网页中去加载动辄几十兆、数百兆的字体是行不通的,那该怎么解决 UI 的诉求呢?

如果能从字体包中把数字抽取出来就好了,按照这个想法,解决问题的方法就转变为如何按需打包字体包。

我们可以使用 font-spider 来实现字体的按需加载。

font-spider 安装

npm install font-spider -g

按需打包字体

创建 demo.html,在 body 中写入要提取的内容“0123456789.$¥”,demo.html 如下

<!-- demo.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>font-spier demo</title>
  <style>
    @font-face {
      font-family: 'demoFont';
      src: url('./fonts/.font-spider/Roboto-BoldCondensed.ttf') format('truetype');
      font-weight: normal;
      font-style: normal;
    }

    html {
      font-family: 'demoFont';
    }
  </style>
</head>
<body>
  0123456789.$¥
</body>
</html>

运行font-spider命令,打包出精简版的字体文件

font-spider ./demo.html

由于我们只用到了数字相关的少量文字,打包出来的字体包非常小,只有 5kb,完美解决 UI 的需求。

以上就是使用 font-spider 按需打包字体的全部内容,动手试一试吧!

本文地址:https://www.tides.cn/p_node-font-spider

标签: 字体