CSS Font Loading API's FontFaceSet Sample

Available in Chrome 48+ | View on GitHub | Browse Samples

Background

FontFaceSet is an interface defined as part of the CSS Font Loading API. It's used to load font faces, and check the status of previously requested fonts. The FontFaceSet interface for the current HTML page is available in JavaScript as document.fonts.

The sample illustrates constructing FontFace objects and explicitly adding them to the page's document.fonts FontFaceSet, which is an alternative to the more traditional approach of using CSS's @font-face rule. It uses the FontFace.loaded promise to keep track of when each individual font has been loaded.

The sample also shows off the newer Set-like functionality in FontFaceSet, by iterating over document.fonts.values() once all the fonts are loaded, and displaying information about each FontFace.

Live Output

I'm using the font-family Bitter!

I'm using the font-family Oxygen!


CSS Snippet

.bitter {
  font-family: Bitter;
}

.oxygen {
  font-family: Oxygen;
}

JavaScript Snippet

function logLoaded(fontFace) {
  ChromeSamples.log(fontFace.family, 'loaded successfully.');
}

// Loading FontFaces via JavaScript is alternative to using CSS's @font-face rule.
var bitterFontFace = new FontFace('Bitter', 'url(https://fonts.gstatic.com/s/bitter/v7/HEpP8tJXlWaYHimsnXgfCOvvDin1pK8aKteLpeZ5c0A.woff2)');
document.fonts.add(bitterFontFace);
bitterFontFace.loaded.then(logLoaded);
var oxygenFontFace = new FontFace('Oxygen', 'url(https://fonts.gstatic.com/s/oxygen/v5/qBSyz106i5ud7wkBU-FrPevvDin1pK8aKteLpeZ5c0A.woff2)');
document.fonts.add(oxygenFontFace);
oxygenFontFace.loaded.then(logLoaded);

// The .ready promise resolves when all fonts that have been previously requested
// are loaded and layout operations are complete.
document.fonts.ready.then(function() {
  ChromeSamples.log('There are', document.fonts.size, 'FontFaces loaded.\n');

  // document.fonts has a Set-like interface. Here, we're iterating over its values.
  for (var fontFace of document.fonts.values()) {
    ChromeSamples.log('FontFace:');
    for (var property in fontFace) {
      ChromeSamples.log('  ' + property + ': ' + fontFace[property]);
    }
    ChromeSamples.log('\n');
  }
});