Google's Web Fonts API offers a way to define callback functions to be executed if a font has finished loading, or couldn't be loaded etc. Is there a way to achieve something similar using CSS3 web fonts (@font-face)?
Chrome 35+ and Firefox 41+ implement the CSS font loading API (MDN, W3C). Call document.fonts
to get a FontFaceSet object, which has a few useful APIs for detecting the load status of fonts:
check(fontSpec)
- returns whether all fonts in the given font list have been loaded and are available. The fontSpec
uses the CSS shorthand syntax for fonts.document.fonts.check('bold 16px Roboto'); // true or false
document.fonts.ready
- returns a Promise indicating that font loading and layout operations are done.document.fonts.ready.then(function () { /*... all fonts loaded...*/ });
Here's a snippet showing these APIs, plus document.fonts.onloadingdone
, which offers extra information about the font faces.
alert('Roboto loaded? ' + document.fonts.check('1em Roboto')); // false
document.fonts.ready.then(function () {
alert('All fonts in use by visible text have loaded.');
alert('Roboto loaded? ' + document.fonts.check('1em Roboto')); // true
});
document.fonts.onloadingdone = function (fontFaceSetEvent) {
alert('onloadingdone we have ' + fontFaceSetEvent.fontfaces.length + ' font faces loaded');
};
<link href='https://fonts.googleapis.com/css?family=Roboto:400,700' rel='stylesheet' type='text/css'>
<p style="font-family: Roboto">
We need some text using the font, for the font to be loaded.
So far one font face was loaded.
Let's add some <strong>strong</strong> text to trigger loading the second one,
with weight: 700.
</p>
IE 11 doesn't support the API. Look at available polyfills or support libraries if you need to support IE: