Hacker News 中文摘要

RSS订阅

如何自托管Google Fonts中的网页字体 -- How to self-host a web font from Google Fonts

文章摘要

文章介绍了如何从Google Fonts自托管网页字体,建议下载字体文件并上传到自己的服务器,而不是直接使用Google提供的嵌入代码,以避免泄露访问者IP地址。同时提醒用户确保字体使用符合相关许可协议。

文章总结

如何从Google Fonts自托管网页字体

在网页设计中,Google Fonts是一个常用的字体来源。然而,直接使用Google Fonts提供的嵌入代码可能会导致访问者的IP地址泄露给Google。为了避免这种情况,建议将字体文件下载并托管在自己的服务器上。

步骤如下:

  1. 确保字体使用符合许可证要求
    在使用任何字体之前,务必确认其许可证允许自托管。

  2. 下载字体文件

    • 访问Google Fonts并搜索所需字体。
    • 选择“获取字体”,然后点击“获取嵌入代码”(不要直接使用该代码)。
    • 在生成的HTML代码中,找到类似<link href="https://fonts.googleapis.com/css2?family=Fira+Code&display=swap" rel="stylesheet">的链接。
    • 使用该链接下载CSS文件,并进一步下载CSS文件中引用的所有字体文件。
  3. 整理字体文件

    • 将所有下载的字体文件放入一个文件夹中,建议使用带有更新日期和长缓存时间的路径(如/Assets/Fira/Code/2025-8-13/)。
    • 将CSS文件复制到该文件夹,并修改CSS文件中的链接为相对路径。
  4. 添加许可证文件

    • 在Google Fonts中找到字体的许可证信息,并将其保存为一个文件。
  5. 在HTML中使用字体

    • 在HTML中添加类似以下代码以引用CSS文件: html <link href="/Assets/Fonts/Fira/Code/2025-8-13/fira-code.css" rel="preload"> <link href="/Assets/Fonts/Fira/Code/2025-8-13/fira-code.css" rel="stylesheet">
  6. 在CSS中使用字体

    • 在CSS中添加类似以下代码以应用字体: css code { font-family: "Fira Code", monospace; font-optical-sizing: auto; font-weight: 400; font-style: normal; }
  7. 遵守字体许可证

    • 确保字体的使用符合其许可证要求,并在网页中添加许可证链接。

参考示例
如果对上述步骤有疑问,可以参考此示例

其他信息
- 本博客使用的字体包括Fira Code和Noto Sans,分别使用此许可证此许可证。 - 本博客内容(除图标、JavaScript和字体外)采用CC-BY-SA 4.0许可证。

通过以上步骤,您可以安全地自托管Google Fonts中的字体,避免隐私泄露问题。

评论总结

评论主要围绕自托管Google字体的优缺点展开,观点多样,以下是总结:

支持自托管字体的观点: 1. 隐私保护:部分用户认为自托管可以避免用户数据被Google收集。
- "I don’t want every visitor to send a piece of information about themselves to Google just to get some fonts."(rs186) - "there’s no need to do a ‘phone home’ roundtrip to google only to present some fonts."(rambambram)

  1. 技术控制:自托管可以更好地控制字体加载和优化网页性能。
    • "Even better download it, subset it then base64 encode it into your CSS for zero FOUC."(damieng)
    • "It lets you pick from the Google Fonts catalog, and comes with various options for further reducing the fonts’ sizes."(valadaptive)

反对自托管字体的观点: 1. 复杂性:自托管增加了技术复杂性,且可能没有必要。
- "What benefits are you getting from this? I mean have you built an entire CDN to cache the fonts so that your server does not have to download it every time a new page is loaded?"(dktalks) - "But doesn’t Google serve a different font depending on the User Agent string?"(nick_)

  1. Google的隐私声明:Google声称其字体服务不会收集用户数据。
    • "Google does not use any information collected by Google Fonts to create profiles of end users or for targeted advertising."(xp84)

其他观点: 1. 技术复古:部分用户认为自托管字体的讨论是“老技术新用”。
- "It’s like people are rediscovering CSS from 20 years ago."(gethly) - "Everything old is new again."(rambambram)

  1. 工具推荐:用户推荐了一些自托管字体的工具和资源。
    • "I use google-webfonts-helper to get google fonts."(SigmundurM)
    • "FontSource releases all of google fonts and more as NPM packages."(WebBurnout)

总结:自托管字体的讨论集中在隐私、技术控制和复杂性之间的权衡,部分用户认为这是不必要的复杂化,而另一些用户则强调其隐私和性能优势。