整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

压缩HTML引用字体

例简介

有些网站为了凸显某部分字体,而引入自定义字体,但由于自定义字体相对都比较大(几M),导致页面加载缓慢;所以本文介绍三种压缩字体的方法,可根据项目情况自行选择。


压缩方法

1、利用Fontmin程序(效果如下图)

1)运行Fontmin程序后,1位置输入需要生成的文字内容,2位置拖入ttf文件(源文件7947KB);

2)点击“生成”按钮,生成成功后,弹出生成文件(ttf文件变成11KB),根据浏览器兼容性引入文件。

Tips:当需要增加新的文字时,需要重新生成文件。

2、利用Node.js+Fontmin组件(效果如下图)


1)配置好Node.js框架(本文使用Express);

2)在index.js文件增加代码,用来自动读取“views”下面的所有*.ejs文件的文字,然后根据“src”的ttf源文件,使用Fontmin组件生成压缩文件(生成目录“dest”)。

Tips:适用于多文件情况下,自动汇总生成。

// 遍历所有文件提取里面的所有文字
const fs = require("fs");
const Fontmin = require('fontmin');
let set = new Set();


//get all possible characters
const scanFolder = (dir, done) => {
    let results = [];
    fs.readdir(dir, (err, list) => {
        if (err) {
            return done(err);
        }
        let i = 0;
        (function iter() {
            let file = list[i++];
            if (!file) {
                return done(null, results);
            }
            file = dir + '/' + file;
            console.log(file)
            fs.stat(file, (err, stat) => {
                if (stat && stat.isDirectory()) {
                    scanFolder(file, (err, res) => {
                        results = results.concat(res);
                        iter();
                    });
                } else {
                    results.push(file);
                    iter();
                }
            });
        })();
    });
};
//get all possible characters
const generateFinalHTML = finalString => {
    const fontmin = new Fontmin()
        .src('public/fonts/SourceHanSansCN-Medium.ttf')
        .dest('public/fonts/build/')
        .use(Fontmin.glyph({
            text: finalString,
            hinting: false
        }))
        .use(Fontmin.ttf2woff({
            deflate: true
        }));




    fontmin.run((err) => {
        if (err) {
            throw err;
        }
    });
}
//get all possible characters
scanFolder("views", (n, results) => {
    results.forEach(file => {
        const result = fs.readFileSync(file, 'utf8');
        const currentSet = new Set(result)
        set = new Set([...set, ...currentSet]);
    });
    generateFinalHTML(Array.from(set).join(""))
})

3、利用font-spider组件(效果如下图)

1)安装font-spider组件;

npm install font-spider -g

2)新建index.html文件;

3)执行下面命令生成压缩文件。

font-spider ./*.html


总结

可以根据项目实际情况,选择适当的方法。

、网上下载'ttf'字体


二、在项目中使用

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      @font-face {
        font-family: 'homeFont';
        src: url('./siyuan.ttf');
        font-weight: normal;
        font-style: normal;
      }
      p {
        font-family: 'homeFont';
      }
    </style>
  </head>
  <body>
    <p>好</p>
  </body>
</html>


三、下载压缩字体依赖

npm install font-spider -g

# 查看版本号
font-spider -V


四、如果是vue中字体需要压缩,需要自己在外新建一个文件夹来存放压缩字体。

打开终端,输入命令

font-spider index.html


五、复制.font-splider中字体到vue项目进行替换

事背景:
UI设计师UI界面设计中部分展示内容使用了特殊字体,要求实际页面也用同字体展示该内容,但目前存在的问题是该指定字体体积较大,实际生产中页面加载该字体库可能存在加载缓慢问题!

如何解决呢?

我们的第一反应就是压缩字体,但实际测试中一款完整的字体库即使压缩了效果也不理想!今天老码给大家推荐的这款工具库就是只提取出待使用的字符对应字体工具,简单来说页面展示内容都有哪些字符,就只提取出这些字符字体,从而减少字体体积!没错,今天的主角就是 fontmin

https://github.com/ecomfe/fontmin

其官网的使用说明也很简单,很容易入手!

安装

npm install --save fontmin

官网也提供了一些有用的插件

glyph — Compress ttf by glyph.
ttf2eot — Convert ttf to eot.
ttf2woff — Convert ttf to woff.
ttf2woff2 — Convert ttf to woff2.
ttf2svg — Convert ttf to svg.
css — Generate css from ttf, often used to make iconfont.
svg2ttf — Convert font format svg to ttf.
svgs2ttf — Concat svg files to a ttf, just like css sprite.
otf2ttf — Convert otf to ttf.

我们的解决思路就是提供完整的字体库ttf或者otf, 要展示的文本内容所有字符,最终生成我们需要的web字体及样式, 这里分享出老码的工程化示例

const Fontmin = require('fontmin')

const fontmin = new Fontmin()
    .src('./fonts/T2.ttf')  //完整的字体库
    .use(Fontmin.otf2ttf())
    .use(Fontmin.glyph({
        text: "0123456789" //要展示的文本内容
    }))
    .use(Fontmin.ttf2eot({
        clone: true
    }))
    .use(Fontmin.ttf2woff({
        clone: true
    }))
    .use(Fontmin.ttf2woff2())
    .use(Fontmin.ttf2svg({
        clone: true
    }))
    .use(Fontmin.css({
        fontFamily: 'x2',  //指定最终生成样式字体名
        base64: false,
    }))
    .dest('./dist/')

fontmin.run(function (err) {
    if (err) {
        console.log(err)
    }
})

效果截图


生成的样式

@font-face {
    font-family: "x2";
    src: url("T2.eot"); /* IE9 */
    src: url("T2.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
    url("T2.woff2") format("woff2"), /* chrome 36+, firefox 39+,iOS 10+, Android 67+ */
    url("T2.woff") format("woff"), /* chrome, firefox */
    url("T2.ttf") format("truetype"), /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */
    url("T2.svg#x2") format("svg"); /* iOS 4.1- */
    font-style: normal;
    font-weight: normal;
}


html预览测试

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
	<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0,viewport-fit=cover">
	<link rel="stylesheet" href="T2.css">
	<style>
		body {
			font-family: "x2";
		}
	</style>
</head>
<body>
<div>6789</div>
</body>
</html>


实际最终生成的T2.ttf由最初1.3M降低到31K

额外功能,看图发挥想象~~~~~


类似GUI工具推荐:

  • fontmin-app
https://github.com/ecomfe/fontmin-app

点赞、关注老码每天分享!