Font Loading API
The CSS Font Loading API provides events and interfaces for dynamically loading font resources. It gives you more control over the font loading process than standard CSS @font-face rules, allowing you to prevent Flash of Invisible Text (FOIT) or Flash of Unstyled Text (FOUT) and load fonts for use in Canvas.
1. The FontFace Object
The FontFace interface represents a single usable font face. You can create it programmatically.
// new FontFace(family, source, descriptors)
const myFont = new FontFace('MyCustomFont', 'url(my-font.woff2)', {
style: 'normal',
weight: '700'
});
2. Loading the Font
Creating the object doesn't load it immediately. You must call load(), which returns a Promise.
myFont.load().then((loadedFace) => {
// Font loaded successfully
document.fonts.add(loadedFace);
document.body.style.fontFamily = 'MyCustomFont, sans-serif';
}).catch((error) => {
console.error('Font loading failed:', error);
});
3. document.fonts (FontFaceSet)
The document.fonts property is a FontFaceSet interface that manages the fonts used by the document.
Checking if a font is ready
You can check if a specific font string is ready to be rendered.
if (document.fonts.check('12px MyCustomFont')) {
console.log('Font is available');
}
Waiting for all fonts
You can wait for all fonts in the document to finish loading.
document.fonts.ready.then(() => {
console.log('All fonts are loaded and ready');
});
4. Use Case: Canvas
When drawing text to a <canvas>, the font must be loaded before you draw, otherwise, the browser might draw with a fallback font.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const font = new FontFace('PixelFont', 'url(pixel.woff2)');
font.load().then((loadedFace) => {
document.fonts.add(loadedFace);
ctx.font = '30px PixelFont';
ctx.fillText('Hello World', 10, 50);
});
5. Events
The FontFaceSet fires events during the loading lifecycle.
loading: Fired when the font loading process starts.loadingdone: Fired when all fonts have finished loading.loadingerror: Fired when an error occurs.
document.fonts.addEventListener('loading', (event) => {
console.log('Font loading started');
});
programming/javascript/vanilla/javascript programming/javascript/vanilla/canvas-api programming/javascript/vanilla/promises-async-await