首页 > web前端 > css教程 > 最好的字体加载策略以及如何执行它们

最好的字体加载策略以及如何执行它们

Christopher Nolan
发布: 2025-03-26 10:29:09
原创
989 人浏览过

掌握Web字体加载策略:实用指南

扎克·莱瑟曼(Zach Leatherman)的字体加载策略综合指南一直是Web开发人员的宝贵资源。但是,大量的选项可能是压倒性的。本文简化了最佳方法,重点是实用性和执行。

最好的字体加载策略以及如何执行它们

关键策略:

Leatherman拥护两种主要策略:

  1. 与课堂的福特:一种适合大多数情况的多功能方法,无论字体是自托管还是使用字体托管服务。
  2. 关键Foft:最性能的选项,但仅限于自托管字体。

在深入研究之前,让我们澄清术语:

  • FOIT(无形文本的闪光):文本被隐藏在Web字体加载之前。
  • Fout(未风格的文本闪光灯):最初显示系统字体,然后由Web字体替换。
  • Foft(人造文本闪光灯):一种更复杂的方法,涉及首先加载罗马字体,然后再加载其他样式。

字体托管选项:

  1. 云提供商(例如,Google字体,Adobe字体):通常更易于实现,但由于阻碍行为而效果通常更低。 Google字体的display=swap参数通过启用Fout提供了略有改进。

    <link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet">
    登录后复制
  2. 自我托管:需要字体许可,并涉及使用@font-face以及可能的font-display: swap 。这允许更大的控制和优化。

自托管字体和实施:

@font-face允许在CSS中声明字体:

 @font-face {
  字体家庭:Lato;
  src:url('to to to to-lato.woff2')格式('woff2'),
       URL('to to to-lato.woff')格式('woff');
  / * ...其他重量和样式... */
}

html {
  字体家庭:Lato,sans-serif;
}
登录后复制

font-display: swap触发Fout for自托管字体。

fout with class(既适用于云和自主字体):

该策略使用JavaScript使字体异步加载,将重新涂片分组并适应用户偏好。如果用户已经安装了字体,它还允许跳过字体加载。

  1. 正常加载字体(通过<link>用于云托管或@font-face以进行自构托)。

  2. 在A中使用CSS字体加载API(或FontfaceObserver以更广泛的兼容性)<script> tag:</script>

    if ('fonts' in document) {
      Promise.all([
        document.fonts.load('1em Lato'),
        // ... other weights and styles ...
      ]).then(_ => {
        document.documentElement.classList.add('fonts-loaded');
      });
    }
    登录后复制
  3. Use CSS to style the text:

    body {
      font-family: sans-serif; /* System font */
    }
    
    .fonts-loaded body {
      font-family: Lato, sans-serif; /* Web font */
    }
    登录后复制
  4. Optimize for repeat visits using sessionStorage:

    if (sessionStorage.fontsLoaded) {
      document.documentElement.classList.add('fonts-loaded');
    } else {
      // ... font loading code ...
    }
    登录后复制

FOFT (Flash of Faux Text):

This advanced technique loads the Roman font first, then other styles. "Critical FOFT" optimizes this by loading only essential characters initially. While offering performance gains, it's more complex to implement.

Choosing the Right Strategy:

  • Cloud-Hosted, Simple: Use font-display: swap if provided by the host; otherwise, use FOUT with Class.
  • Self-Hosted, Simple: @font-face font-display: swap is the easiest approach, especially for a small number of font files.
  • Self-Hosted, Advanced: Consider Standard FOFT or Critical FOFT for performance optimization, especially with many font files.

This streamlined guide provides a clear path to choosing and implementing the optimal font loading strategy for your project. Remember to prioritize a JavaScript-free approach when feasible, particularly with limited font files.

以上是最好的字体加载策略以及如何执行它们的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板