Font Loading API
What you'll learn: How to use JavaScript to detect when fonts have loaded and control text rendering programmatically.
While font-display (lesson 567) lets you declare font loading behavior in CSS, the Font Loading API gives you JavaScript-level control. This means you can run code when fonts finish loading, show custom loading states, or even prevent rendering until critical fonts are ready.
Why Use the Font Loading API?
You've already learned about FOIT (flash of invisible text) and FOUT (flash of unstyled text). Sometimes you need more control than CSS alone provides—maybe you want to show a loading spinner, or coordinate font loading with other page assets.
The Core Interface
The API centers around document.fonts, which is a FontFaceSet object:
// Check if a specific font is ready
document.fonts.ready.then(() => {
console.log('All fonts have loaded!');
});
You can also load fonts programmatically:
// Force a font to load
document.fonts.load('1rem "Open Sans"').then(() => {
console.log('Open Sans is ready');
// Now safe to render critical text
});
Or check loading status:
if (document.fonts.check('1rem "Open Sans"')) {
console.log('Font already loaded');
}
Practical Example
document.fonts.ready.then(() => {
// Remove loading class, show content
document.body.classList.remove('fonts-loading');
});
Key Takeaway: The Font Loading API lets you detect and control font loading with JavaScript, enabling custom loading states and better coordination between fonts and your page's rendering strategy.