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

简述

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

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
相关推荐
rockey6272 小时前
C#脚本引擎之AScript与Jurassic、Jint对比
javascript·c#·.net·js·script·动态脚本
Profile排查笔记3 小时前
指纹浏览器哪个好?从 Profile、代理、权限和自动化能力判断是否适合
前端·人工智能·后端·自动化
lzhdim4 小时前
12、JavaScript常见的内存泄露问题 - JavaScript学习系列文章
开发语言·前端·javascript·学习·ecmascript
denggun123454 小时前
yield
前端·数据库·python
前端snow4 小时前
ai agent -- prompt汇总
前端
muddjsv6 小时前
前端性能优化实战:从加载到渲染的全面提速指南
前端·性能优化
deli0070076 小时前
JSON 树形查看器:粘贴即解析,折叠展开一目了然
前端·数据库·json·ai编程
guanguan0_06 小时前
PageProxy:页面维度接口地图 + 一键场景切换
前端·ai编程·请求代理·proxy工具
liangshanbo12156 小时前
虚拟列表深度面试题整理
java·开发语言·前端
IT_陈寒7 小时前
Redis内存警告竟是因为这个不起眼的配置项
前端·人工智能·后端