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

简述

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

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
相关推荐
IT_陈寒2 小时前
Python开发者必知的5大性能陷阱:90%的人都踩过的坑!
前端·人工智能·后端
codingWhat3 小时前
介绍一个手势识别库——AlloyFinger
前端·javascript·vue.js
Lee川3 小时前
深度拆解:基于面向对象思维的“就地编辑”组件全模块解析
javascript·架构
代码老中医3 小时前
2026年CSS彻底疯了:这6个新特性让我删掉了三分之一JS代码
前端
进击的尘埃3 小时前
Web Worker 与 OffscreenCanvas:把主线程从重活里解放出来
javascript
不会敲代码13 小时前
Zustand:轻量级状态管理,从入门到实践
前端·typescript
踩着两条虫3 小时前
VTJ.PRO 双向代码转换原理揭秘
前端·vue.js·人工智能
扉川川3 小时前
OpenClaw 架构解析:一个生产级 AI Agent 是如何设计的
前端·人工智能
远山枫谷3 小时前
一文理清页面/组件通信与 Store 全局状态管理
前端·微信小程序
codingWhat3 小时前
手撸一个「能打」的 React Table 组件
前端·javascript·react.js