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

简述

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

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

font-spider有如下特性:

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

安装

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

  1. 新建文件夹spider

  2. 初始化package.json

csharp 复制代码
npm init -y
  1. 安装:
css 复制代码
npm install font-spider

使用

  1. spider目录下新建index.html
xml 复制代码
<!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. 执行以下代码:

scss 复制代码
// 语法
npx font-spider [options] <htmlFile1 htmlFile2 ...>

// 使用
npx font-spider index.html

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

参考文档

官方地址:

ruby 复制代码
// 官网(可能需要翻墙)
http://font-spider.org
// github 地址
https://github.com/aui/font-spider/blob/master
相关推荐
山峰哥13 小时前
SQL慢查询调优实战:从全表扫描到索引覆盖的完整复盘
前端·数据库·sql·性能优化
红尘散仙13 小时前
一个 `#[uniffi::export]`,把 Rust 接进 React Native
前端·后端·rust
moshuying13 小时前
AI Coding 最大的 token 黑洞,可能根本不是 prompt
前端
红尘散仙13 小时前
一行 `#[specta::specta]`,让 Tauri IPC 有类型
前端·后端·rust
lichenyang45313 小时前
HarmonyOS HMRouter 接入记录:从普通 Tab Demo 到路由跳转
前端
木斯佳14 小时前
前端八股文面经大全:腾讯WXG暑期前端一面(2026-05-15)·面经深度解析
前端·面试·笔试
canonical_entropy14 小时前
NOP Chaos Flux 架构演变史:从 AMIS 重写到现代低代码运行时
前端·aigc·ai编程
张元清15 小时前
useEffect 之外:专门处理异步、深比较和 SSR 的 Effect Hook
前端·javascript·面试
小小小小宇15 小时前
前端双Token机制无感刷新(二)
前端
XinZong15 小时前
OpenClaw 中最经典的 6 款skill,真正能进工作流的 skills
javascript·后端