压缩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

总结

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

猜你喜欢

转载自blog.csdn.net/king0964/article/details/130430563
今日推荐