Font Face Observer
Font Face Observer gives you control over web font loading using a simple promise based interface. It doesn’t matter where your fonts come from: host them yourself, or use a web font service such as Google Fonts, Typekit, Fonts.com, and Webtype.
To keep things simple, let’s assume you have the following @font-face
rule somewhere in your style sheet.
@font-face {
font-family: Output Sans;
src: url(output-sans.woff2) format('woff2'),
url(output-sans.woff) format('woff');
}
You load this web font by creating a new FontFaceObserver
instance and calling its load
method.
var font = new FontFaceObserver('Output Sans');
font.load().then(function () {
console.log('Output Sans has loaded.');
});
This will load the font and return a promise that is resolved when the font has loaded, or rejected if the font fails to load. That’s all there is to it.
You can use npm to install the fontfaceobserver
module. Font Face Observer is also available on Bower and installable through jspm.
$ npm install fontfaceobserver --save
You can then load the module by requiring it in your code.
var FontFaceObserver = require('fontfaceobserver');
Not using modules?
You can also download a copy and manually include it in your project. You can then use the global FontFaceObserver constructor to load your fonts.
The fontfaceobserver
module exposes a single constructor that takes two parameters: a family name and an optional font description object.
The font description object may contain three optional properties: weight
, style
, and stretch
. The values of these properties should match the web font you’re trying to load. If a property is not present it will default to normal
.
var font = new FontFaceObserver('Output Sans', {
weight: 300,
style: 'italic'
});
To load a font, call the load
method on a FontFaceObserver
instance. It’ll return a promise that resolves when the font loads, or rejected when the font fails to load.
var font = new FontFaceObserver('Output Sans');
font.load().then(function () {
console.log('Output Sans has loaded.');
}).catch(function () {
console.log('Output Sans failed to load.');
});
If your font doesn’t contain latin characters Font Face Observer may not be able to load it. In this case you should pass a custom string to the load
method. The string should contain characters that are present in the font.
var font = new FontFaceObserver('Source Han Sans');
font.load('中国').then(function () {
console.log('Source Han Sans has available');
});
Font Face Observer supports the following browsers: Chrome, Firefox, Opera, Safari, Internet Explorer 8 and above, Edge, and the Android browser.