掌握Web字体加载策略:实用指南
扎克·莱瑟曼(Zach Leatherman)的字体加载策略综合指南一直是Web开发人员的宝贵资源。但是,大量的选项可能是压倒性的。本文简化了最佳方法,重点是实用性和执行。
关键策略:
Leatherman拥护两种主要策略:
在深入研究之前,让我们澄清术语:
字体托管选项:
云提供商(例如,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">
自我托管:需要字体许可,并涉及使用@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使字体异步加载,将重新涂片分组并适应用户偏好。如果用户已经安装了字体,它还允许跳过字体加载。
正常加载字体(通过<link>
用于云托管或@font-face
以进行自构托)。
在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'); }); }
Use CSS to style the text:
body { font-family: sans-serif; /* System font */ } .fonts-loaded body { font-family: Lato, sans-serif; /* Web font */ }
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:
font-display: swap
if provided by the host; otherwise, use FOUT with Class.@font-face
font-display: swap
is the easiest approach, especially for a small number of 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中文网其他相关文章!