优化字体加载
实现 `font-display`、预加载和子集化,确保 Web 字体高效加载且不会造成布局偏移。
优化字体加载 是 CoddyKit 上的免费 Web Performance Optimization & Lighthouse 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web Performance Optimization & Lighthouse 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web Performance Optimization & Lighthouse 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Optimize Fonts?
Web fonts make websites beautiful and unique, but they can also be a major source of performance bottlenecks. Large font files mean longer download times, which directly impacts your site's overall speed and user experience.
Slow font loading can lead to issues like 'Flash of Unstyled Text' (FOUT) or 'Flash of Invisible Text' (FOIT). In this lesson, we'll learn practical techniques to load fonts efficiently.
Control Font Loading with `font-display`
The font-display CSS property gives you control over how web fonts load and display. It tells the browser what strategy to use while a font is still downloading, helping to prevent jarring visual shifts.
auto: The browser's default behavior.block: Short block period (invisible text), then infinite swap.swap: Very short block period (invisible text), then infinite swap.fallback: Very short block, then short swap, then permanent fallback.optional: Very short block, no swap, permanent fallback.
`font-display: swap` in Action
font-display: swap is a popular choice for balancing performance and aesthetics. It tells the browser to use a fallback font immediately. Once your custom web font is downloaded, it 'swaps' in, replacing the fallback.
This ensures text is always visible, prioritizing content readability over font styling during the initial load.
@font-face {
font-family: 'MyWebFont';
src: url('mywebfont.woff2') format('woff2');
font-display: swap;
}`optional` and `fallback` Strategies
Other font-display values offer different trade-offs:
fallback: Gives the custom font a very short block period (around 100ms) and a short swap period (around 3s). If the custom font isn't ready within these times, it uses a fallback font permanently.optional: Similar tofallback, but the browser decides if the custom font is downloaded at all, based on network conditions. If the font is not downloaded quickly, the fallback is used permanently, avoiding any layout shift.
Preloading Critical Fonts
Normally, browsers discover fonts when they parse your CSS. However, you can tell the browser to fetch a resource *earlier* than it would normally discover it using preloading.
For fonts, <link rel="preload"> means the browser can start downloading them even before the CSS that uses them is fully parsed. This significantly reduces the time until text is displayed with the correct font.
How to Preload a Font
You can preload fonts by adding a <link> tag in your HTML's <head> section. It's crucial to include as="font" and crossorigin to ensure the font is fetched correctly and to prevent double downloads.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Preload Font Example</title>
<link rel="preload" href="mywebfont.woff2" as="font" type="font/woff2" crossorigin>
<style>
@font-face {
font-family: 'MyWebFont';
src: url('mywebfont.woff2') format('woff2');
font-display: swap;
}
body {
font-family: 'MyWebFont', sans-serif;
}
</style>
</head>
<body>
<h1>Hello CoddyKit!</h1>
<p>This text uses a preloaded web font.</p>
</body>
</html>Reducing Font Size with Subsetting
Font files often contain hundreds, or even thousands, of characters. Many of these, like special symbols or characters for different languages, might not be used on your specific website.
Font subsetting is the process of creating a smaller version of a font file that only includes the specific characters (glyphs) your website actually needs. This drastically reduces the file size.
Why Subset Your Fonts?
Subsetting has a direct and significant impact on your website's performance:
- Faster Downloads: Smaller font files download much quicker, leading to improved page load times.
- Reduced Bandwidth: This saves data for your users, which is especially important for those on mobile plans.
- Better User Experience: Less waiting means users see your content, styled correctly, much faster.
Tools like Font Squirrel's Webfont Generator or Google Fonts can help you subset.
Test Your Font Knowledge
Which of the following are effective strategies for optimizing web font loading and performance?
Font Loading Recap
We've covered essential techniques for optimizing web font loading:
font-display: This CSS property controls how fonts render during download, preventing FOUT and FOIT.- Preloading: Using
<link rel="preload">in your HTML fetches critical fonts earlier, speeding up their availability. - Subsetting: Reduces font file size by including only the characters your website actually needs.
By applying these strategies, you can significantly improve your website's perceived performance and deliver a smoother user experience.
常见问题解答
「优化字体加载」课时是免费的吗?
是的 — 「优化字体加载」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web Performance Optimization & Lighthouse 课程的其余内容,请升级到 CoddyKit PRO。 Web Performance Optimization & Lighthouse 课程共包含 4 节课。
「优化字体加载」这节课中我会学到什么?
实现 `font-display`、预加载和子集化,确保 Web 字体高效加载且不会造成布局偏移。 你通过在浏览器中直接运行的动手代码来练习 Web Performance Optimization & Lighthouse,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Web Performance Optimization & Lighthouse 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Web Performance Optimization & Lighthouse 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「优化字体加载」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Web Performance Optimization & Lighthouse 课中编写并运行代码吗?
能。每节 Web Performance Optimization & Lighthouse 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。