使用python 调用 FontForge 压缩 Font awesome 图标字体,加快网页加载速度 [复制链接]

帖子链接已复制到剪贴板
fireblood (UID: 3493) 2023-3-4
帖子已经有人评论啦,不支持删除!

1174 1

理论上适用于任何字体。

 

实际上测试,有的字体设计内部存在bug, 调用不成功。 个人blog成功案例

 

一: 下载安装 FontForge

Windows, Mac and GNU+Linux.

 

二 Python 脚本

minify.py 文件

import glob
import re
import fontforge


extensions = [".html", ".js"]
pattern = re.compile("(fa-[-\w]+)")


# 获取使用到的图标
def get_used_icons(path):
    icon_dict = {}
    for filename in glob.glob(path, recursive=True):
        for extension in extensions:
            if extension in filename:
                for line in open(filename, encoding='utf-8'):
                    for match in re.finditer(pattern, line):
                        icon_dict[match.group()[3:]] = True
    return icon_dict


# 去除除了传入的字典的图标
def minify(path, used_dict):
    font = fontforge.open(path)
    assert isinstance(font, fontforge.font)
    selection = font.selection
    assert isinstance(selection, fontforge.selection)
    selection.all()
    for i in selection.byGlyphs:
        assert isinstance(i, fontforge.glyph)
        if i.glyphname not in used_dict:
            font.removeGlyph(i)
    font.generate(path)


if __name__ == '__main__':
    web_path = "V:/hexo/blog/public/**"
    font_path = "V:/hexo/blog/themes/matery/source/libs/awesome/webfonts/"
    font_list = ["fa-brands-400.woff2", "fa-regular-400.woff2", "fa-solid-900.woff2"]
    used_icon_dict = get_used_icons(web_path)
    for font_name in font_list:
        minify(font_path + font_name, used_icon_dict)

三: 运行压缩脚本

D:\Program Files (x86)\FontForgeBuilds>bin\ffpython.exe d:\Work\Dev\minifyFont\minify.py

 

压缩结果 可以看到 字体 https://blog.17lai.site/libs/awesome/webfonts/fa-brands-400.woff2 压缩到个位数KB, 原大小100多KB!

 

四: 字体 css 压缩 

 

下面是另一个 css 压缩脚本,调试运行还有问题,谁有空debug 调试一下?

 

css 文件地址 :

 

https://blog.17lai.site/libs/awesome/css/all.min.css

 

miniCSS.py

 

import cssutils

# 读取 CSS 文件
with open('/app/themes/matery/source/libs/awesome/css/all.css', 'r') as f:
    css_text = f.read()

# 解析 CSS 文件
sheet = cssutils.parseString(css_text)

# 选择器字典
selector_dict = {'fa-brands-400': True, 'fa-regular-400': True, 'fa-solid-900': True, 'fa-bars': True, 'fa-home': True, 'fa-suitcase': True, 'fa-mask': True, 'fa-music': True, 'fa-chevron-down': True, 'fa-image': True, 'fa-film': True, 'fa-folder-plus': True, 'fa-tags': True, 'fa-bookmark': True, 'fa-archive': True, 'fa-link': True, 'fa-toolbox': True, 'fa-telegram-plane': True, 'fa-terminal': True, 'fa-laptop-code': True, 'fa-cloud': True, 'fa-tools': True, 'fa-id-badge': True, 'fa-user-circle': True, 'fa-address-card': True, 'fa-pen-nib': True, 'fa-exclamation-circle': True, 'fa-search': True, 'fa-sun': True, 'fa-fw': True, 'fa-chevron-right': True, 'fa-chart-area': True, 'fa-eye': True, 'fa-users': True, 'fa-github': True, 'fa-docker': True, 'fa-envelope-open': True, 'fa-rss': True, 'fa-times-circle': True, 'fa-arrow-up': True, 'fa-lg': True, 'fa-comment': True, 'fa-street-view': True, 'fa-camera-retro': True, 'fa-info-circle': True, 'fa-bar-chart': True, 'fa-gift': True, 'fa-linux': True, 'fa-blog': True, 'fa-wrench': True, 'fa-book': True, 'fa-clock': True, 'fa-angle-left': True, 'fa-angle-right': True, 'fa-pencil': True, 'fa-cloud-upload': True, 'fa-cog': True, 'fa-2x': True, 'fa-icon能正常显示了': True, 'fa-moon-o': True, 'fa-lightbulb-o': True, 'fa-moon': True, 'fa-bellaria-hidden': True, 'fa-list': True, 'fa-comments': True, 'fa-3x': True, 'fa-4x': True, 'fa-5x': True, 'fa-edge': True, 'fa-scribd': True, 'fa-google': True, 'fa-chrome': True, 'fa-opera': True, 'fa-rotate-270': True, 'fa-heading': True, 'fa-times': True, 'fa-circle-notch': True, 'fa-italic': True, 'fa-gem': True, 'fa-arrow-left': True, 'fa-arrow-right': True, 'fa-download': True, 'fa-upload': True, 'fa-youtube-play': True, 'fa-list-alt': True, 'fa-address-book': True, 'fa-user-circle-o': True, 'fa-facebook': True, 'fa-twitter': True, 'fa-google-plus': True, 'fa-linkedin': True, 'fa-tumblr': True, 'fa-medium': True, 'fa-slack': True, 'fa-weibo': True, 'fa-wechat': True, 'fa-qq': True, 'fa-calendar-minus': True, 'fa-calendar-check': True, 'fa-file-word': True, 'fa-expand': True, 'fa-user': True, 'fa-copyright': True, 'fa-dot-circle': True, 'fa-circle-o-notch': True, 'fa-spin': True, 'fa-font': True, 'fa-angle-up': True, 'fa-angle-down': True, 'fa-share-alt': True, 'fa-ellipsis-v': True, 'fa-align-justify': True, 'fa-angle-double-down': True, 'fa-thumbs-up': True, 'fa-hand-pointer': True, 'fa-clipboard': True, 'fa-chromecast': True, 'fa-w-16': True, 'fa-IR': True, 'fa-list-ul': True, 'fa-chevron-left': True}

# 遍历 CSS 规则的复制
for rule in list(sheet):
    if isinstance(rule, cssutils.css.CSSStyleRule):
        selectors = rule.selectorText.split(',')
        new_selectors = []
        # 遍历选择器
        for selector in selectors:
            selector = selector.strip()
            if selector in selector_dict:
                new_selectors.append(selector)
        # 更新规则中的选择器
        if new_selectors:
            rule.selectorText = ','.join(new_selectors)
        else:
            # 如果没有任何选择器,则删除该规则
            sheet.remove(rule)

# 输出处理后的 CSS
with open('style_processed.css', 'w') as f:
    f.write(sheet.cssText)

博客原文地址 

这家伙太懒了,什么也没留下。
已有评论 (1)
提示:您必须 登录 才能查看此内容。
创建新帖
广告推广点击空位自助购买