Webfonts are not always available when your JavaScript runs on first page load. Since fonts may affect element sizes, you may want to know when fonts have been loaded to trigger some kind of recalculation.
Vanilla JavaScript / Modern DOM API
In modern browsers (all but IE and legacy Edge) you can use
document.fonts
Show archive.org snapshot
. Use load
to request a font and receive a Promise that will be resolved once the font is available. Example:
document.fonts.load('1rem "Open Sans"').then(() => { ... })
jQuery / fontSpy
If your project uses jQuery, you could also use jQuery-FontSpy Show archive.org snapshot which also works in IE because it determines the font being loaded by watching for an element's dimensions to change. Example usage:
fontSpy('Open Sans', {
success: function() {
alert('Font has been loaded');
},
failure: function() {
alert('Font failed to load');
}
});
You could also implement something like jQuery-FontSpy in vanilla JS or maybe use vanilla-fontSpy Show archive.org snapshot (we have not used it ourselves).