search
HomeWeb Front-endHTML TutorialWebFont 智能压缩工具——字蛛 1.0.0 正式版发布_html/css_WEB-ITnose

字蛛是一个 WebFont 智能压缩工具,它能自动化分析页面中所使用的 WebFont 并进行按需压缩,通常好几 MB 的中文字体可以被压缩成几 KB 大小。

字蛛主页: http://font-spider.org

字蛛从 2014 年 7 月诞生以来,时隔近两年,终于发布了 v1.0.0 正式版本,改进如下:

  1. 支持绝大多数的中英文 Truetype 字体
  2. 支持开源图标字体库 (New: v1.0.0新特性)
  3. 支持 CSS 伪元素解析,支持 content: "string" 与 content: attr(value) 表达式
  4. 支持远程页面解析,并支持资源映射
  5. 支持四种样式规则:
  6. 支持四种调用方式:命令行、Gulp、Grunt、JS Api
  7. 性能、稳定性大幅提高

新特性:图标字体库压缩

得益于对 CSS 伪元素的支持,除了常规中英文字体压缩之外,v1.0.0 还带来了万众期待的——图标字体压缩支持,能够支持业界流行的开源图标字库。

以 Font Awesome 为例,它是一个典型的开源图标字体项目,目前包含有 628 个图标,并且还不断在添加中。虽然它已经做了很多优化,但字库的体积在移动端来说依然偏大,会影响页面载入速度。使用字蛛可以删除掉字体中没有用到的图标,将字体瘦身。例如一个使用 Font Awesome 的示例页面:

输入 font-spider 命令,启动字蛛进行字体压缩:

经过字蛛分析与压缩处理后, Font Awesome 字体中只保留了页面所用到的 20 个图标,ttf 格式字体体积由 142 KB 降为 6 KB,如果再配合使用 Webpack 等前端工具将字体 Base64 编码后内嵌到 CSS 中,载入速度可以进一步提升。

爬虫实现原理

为什么字蛛能够找到字体中没有使用的字形数据?这里就涉及到对 HTML 与 CSS 的静态分析。

虚拟浏览器技术

字蛛 v1.0.0 版本使用了虚拟浏览器技术来实现 HTML 与 CSS 加载与解析,爬虫模块所依赖的浏览器相关 API 均为它提供。

  • 处理 标签以及资源定位
  • 加载 标签或 @import 语句导入的 CSS 文件
  • 处理 CSS Unicode 字符
  • 管理网络请求,处理资源映射配置
  • 支持 CSS3 选择器、样式表树、文本节点读取

由于虚拟浏览器部分涉及到太多的东西且不是本文重点,所以本文将会略过这部分细节。这部分代码已经分离出来并开源,有兴趣可以去了解: https://github.com/aui/browser-x

操作样式语法树

字蛛是通过解析样式表语法树(CSSOM)来获得 WebFont 信息,在浏览器中可以通过 document.styleSheets 来访问 CSS 的语法树,遍历 CSS 规则的函数实现:

// 遍历 CSS 的规则var eachCssRuleList = (function() {    // 遍历 CSSRuleList    function cssRuleListFor(cssRuleList, callback) {        var index = -1;        var length = cssRuleList.length;        var cssRule, cssStyleSheet;        while (++index < length) {            cssRule = cssRuleList[index];            // 导入的样式规则            if (cssRule instanceof CSSImportRule) {                cssStyleSheet = cssRule.styleSheet;                cssRuleListFor(cssStyleSheet.cssRules || [], callback);            // CSS 媒体查询规则            } else if (cssRule instanceof CSSMediaRule) {                cssRuleListFor(cssRule.cssRules || [], callback);            // 普通的规则            } else {                callback(cssRule);            }        }    }    return function(callback) {        var index = -1;        var styleSheetList = document.styleSheets;        var length = styleSheetList.length;        var cssStyleSheet, cssRuleList;        // 遍历 StyleSheetList        while (++index < length) {            cssStyleSheet = styleSheetList[index];            cssRuleList = cssStyleSheet.cssRules || [];            cssRuleListFor(cssRuleList, callback);        }    };})();

注:浏览器环境不允许访问跨域后的 CSSOM,但虚拟浏览器没有做此限制

查找字体

遍历样式表每一个规则,收集 CSSFontFaceRule 信息:

// 字体信息var webFonts = {};// 字体对应的元素列表var elements = {};// 找到 webFonteachCssRuleList(function(cssRule) {    if (cssRule instanceof CSSFontFaceRule) {        var style = cssRule.style;        var family = style['font-family'];        var src = style.src;        // 保存使用此字体的所有元素列表        elements[family] = [];        // 保存字体信息        webFonts[family] = {            family: family,            src: src,            chars: ''        };    }});

以如下页面作为示例:

<!DOCTYPE html><html lang="zh-CN"><head>    <meta charset="UTF-8">    <title>font-spider</title>    <style>        @font-face {            font-family: 'demo-font';            src: url('./demo-font.ttf');        }        h1.title {            font-family: 'demo-font';        }        h1.title::after {            content: '——海子';        }    </style></head><body>    <h1 id="面朝大海-春暖花开">面朝大海,春暖花开</h1></body></html>

得到 webFonts :

{    "demo-font": {        "family": "demo-font",        "src": "url(\"file:///Users/aui/Documents/demo-font.ttf\")",        "chars": ""    }}

查找字符

利用 document.querySelectorAll() 来获取使用 WebFont 的字符:

// 获取当前节点所使用的 webFontfunction matchFontFamily(cssRule) {    var style = cssRule.style;    var family = style['font-family'];    return webFonts[family];}// 将 fontFace 与元素、字符关联起来eachCssRuleList(function(cssRule) {    if (cssRule instanceof CSSStyleRule) {        var selector = cssRule.selectorText;        var webfont = matchFontFamily(cssRule);        if (webfont) {            // 根据选择器来查找元素            var elems = document.querySelectorAll(selector);            Array.prototype.forEach.call(elems, function(element) {                // 获取元素的文本                webfont.chars += element.textContent;                // 将元素与字体关联起来                elements[webfont.family].push(element);            });        }    }});

此时 webFonts :

{    "demo-font": {        "family": "demo-font",        "src": "url(\"file:///Users/aui/Documents/demo-font.ttf\")",        "chars": "面朝大海,春暖花开"    }}

伪元素

// 处理伪元素,找到继承的 webFonteachCssRuleList(function(cssRule) {    if (cssRule instanceof CSSStyleRule) {        var selector = cssRule.selectorText;        var pseudoName = /\:\:?(?:before|after)$/i;        if (!pseudoName.test(selector)) {            return;        }        // 查找伪元素所在的节点        selector = selector.replace(pseudoName, '');        var elems = document.querySelectorAll(selector);        // 获取伪元素 content 值        var content = cssRule.style.content.replace(/^["']|["']$/g, '');        for (var i = 0; i < elems.length; i ++) {            var elem = elems[i];            for (var family in webFonts) {                // 从伪元素自身不断冒泡,直到找到继承的字体                while (elem) {                    if (elements[family].indexOf(elem) !== -1) {                        webFonts[family].chars += content;                        break;                    }                    elem = elem.parentNode;                }            }        }    }});

此时 WebFont:

{    "demo-font": {        "family": "demo-font",        "src": "url(\"file:///Users/aui/Documents/demo-font.ttf\")",        "chars": "面朝大海,春暖花开————海子"    }}

完整代码在线演示: https://jsfiddle.net/9ont96c4/2

至此,以上例子已经成功演示了字蛛爬虫查找字体、查找文本的工作原理。实际上 HTML 与 CSS 远比上面示例页面复杂,需要处理:

  1. 伪类选择器
  2. font 缩写
  3. 行内样式
  4. 完整的字体匹配算法

由于篇幅有限,上述细节部分可以参见 字蛛爬虫模块源码 。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTML and Code: A Closer Look at the TerminologyHTML and Code: A Closer Look at the TerminologyApr 10, 2025 am 09:28 AM

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

HTML, CSS, and JavaScript: Essential Tools for Web DevelopersHTML, CSS, and JavaScript: Essential Tools for Web DevelopersApr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

The Roles of HTML, CSS, and JavaScript: Core ResponsibilitiesThe Roles of HTML, CSS, and JavaScript: Core ResponsibilitiesApr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.