Sometimes, we want to check if a font (@font-face) has already been loaded with JavaScript.
In this article, we’ll look at how to check if a font (@font-face) has already been loaded with JavaScript.
How to check if a font (@font-face) has already been loaded with JavaScript?
To check if a font (@font-face) has already been loaded with JavaScript, we can listen to a few events emitted by document.fonts
.
For instance, we write
document.fonts.onloading = () => {
// ...
};
document.fonts.onloadingdone = () => {
// ...
};
document.fonts.onloading = () => {
// ...
};
to run the document.fonts.onloading
function when fonts begin to download.
document.fonts.onloadingdone
method runs when fonts are loaded completely.
And document.fonts.onloading
runs when fonts failed to load.
We can also use await document.fonts.ready
to wait for fonts to load.
Conclusion
To check if a font (@font-face) has already been loaded with JavaScript, we can listen to a few events emitted by document.fonts
.