So I have this custom font to load which comes with a very bad jank effect (~ swap effect) and similar problems, such as FOIT (Flash of Invisible Text) or FOUT (Flash of Unstyled Text) or reflow.
Basically, when your div "jump" like the website is listening to Dr Dre ♫⋆。♪˚♬.
The Font load API
There's this JavaScript API called document.fonts.load
that seems to improve the user experience significantly, perhaps prevent any visual delay:
document.fonts.load('1em "MyCustomFont"').then(() => {
console.log('My font is available.');
});
Alternatively, you may leverage promises:
// called when all fonts in the document have been resolved and layout is complete
document.fonts.ready.then(() => {
console.log('My font is ready.');
});
You also get other events to monitor progress and errors.
See official documentation for more details.
The browser support is great:
This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.
The FontFace constructor
You can even add font dynamically using the FontFace constructor:
const font = new FontFace('MyCustomFont', 'url(https://mywebsite.com/myCustomFont.woff2)');
font.load().then(function() {
document.fonts.add(font);
document.body.style.fontFamily = "MyCustom Font, serif";
});
Pros
You may improve performance, loading stuff only when it's necessary (~ asynchronously) and reducing load times.
You may prevent errors, loading stuff only when it's available.
The user experience overall is far better.
Cons
It does not cover other necessary optimizations:
- preloading
- appropriate font fallback
- font displays
- file sizes
- layout shifts
- no js fallback (when JavaScript is disabled)
Actually, you should probably combine this techniques to get significant results.
Wrap this up
This approach provides more granularity and control than CSS FontFace
but should be used in the right context.
Top comments (0)