字体加载 API
用于以编程方式控制字体加载的 JavaScript API(document.fonts),可检查字体是否已加载、预加载特定字体并响应加载事件。
The CSS Font Loading API (exposed as document.fonts in JavaScript) gives you programmatic control over font loading — letting you detect when fonts are ready, load specific fonts on demand, and avoid the flash of unstyled text (FOUT) or invisible text (FOIT) that plagues naive font implementations.
Waiting for fonts before rendering:
// Wait for all fonts to load before revealing content
document.fonts.ready.then(() => {
document.body.classList.add('fonts-loaded');
console.log('All fonts loaded');
});
/* Hide text until fonts are ready */
body { opacity: 0; }
body.fonts-loaded { opacity: 1; transition: opacity 0.2s; }
Checking font status:
// Check if a specific font is loaded
const fontFace = new FontFace('Inter', 'url(/fonts/inter.woff2)');
console.log(fontFace.status); // 'unloaded' | 'loading' | 'loaded' | 'error'
// Check via document.fonts
document.fonts.check('16px Inter'); // Returns boolean
Loading fonts programmatically:
// Create and load a font on demand
const font = new FontFace(
'DisplayFont',
'url(/fonts/display-bold.woff2) format("woff2")',
{ weight: '700', style: 'normal' }
);
font.load().then((loadedFont) => {
// Add to the document's font set
document.fonts.add(loadedFont);
// Now safe to use in CSS or Canvas
document.querySelector('.hero').style.fontFamily = 'DisplayFont, sans-serif';
}).catch((error) => {
console.warn('Font failed to load:', error);
});
Practical pattern — loading fonts for Canvas:
The Font Loading API is especially valuable for <canvas> elements, where fonts must be explicitly loaded before ctx.fillText() renders correctly:
async function drawCanvas(canvas) {
await document.fonts.load('bold 24px Oswald');
const ctx = canvas.getContext('2d');
ctx.font = 'bold 24px Oswald, sans-serif';
ctx.fillText('Chart Title', 20, 40);
}
Iterating over loaded fonts:
// List all loaded font faces
for (const font of document.fonts) {
console.log(font.family, font.weight, font.style, font.status);
}
The API's document.fonts.ready promise is particularly useful for avoiding layout measurement errors. getBoundingClientRect(), canvas text measurement, and scroll position calculations that depend on font metrics can all produce wrong values if called before fonts are available. Using await document.fonts.ready before these operations makes your code resilient to font loading timing.
Browser support is excellent across all modern browsers. For very old browsers, the FontFaceObserver library provides a similar API as a polyfill.