fontsfont-facewebfont-loader

Font Face Observer loading all fonts on page load?


Perhaps I am misunderstanding how Font Face Observer works. My understanding was, this allows you to load fonts ONLY when used. But no matter what font I put in the code, it always loads it into the browser. Example code below. Wouldnt that make my page "heavy" if its loading all the fonts? Especially if Im not using all the fonts? This part of the description confuses me:

Unlike the Web Font Loader Font Face Observer uses scroll events to detect font loads efficiently and with minimum overhead.

That sounds like to me when you scroll down it will detect if a font is being used and if so, loads its. Also if I dont specify a weight, does the font loader for say Roboto load all the available weights?

var fontA = new FontFaceObserver('Roboto');
var fontB = new FontFaceObserver('Roboto Condensed');
var fontC = new FontFaceObserver('Open Sans');
var fontD = new FontFaceObserver('Open Sans Condensed');
var fontE = new FontFaceObserver('Oswald');

fontA.load().then(function () {
  console.log('Roboto font is available');
});

fontB.load().then(function () {
  console.log('Roboto Condensed font is available');
});

fontC.load().then(function () {
    console.log('Open Sans font is available');
});

fontD.load().then(function () {
    console.log('Open Sans Condensed Font is available');
});

fontE.load().then(function () {
    console.log('Oswald font is available');
});

When this runs I see in console:

Roboto font is available
Open Sans font is available
Roboto Condensed font is available
Open Sans Condensed Font is available
Oswald font is available

So to recap, is the purpose of this font loader to load all the fonts I specify? And if I just use the font name without the specific weights, will it load all the weights automatically? Or do I need to also add each weight I want to use for each font?


Solution

  • What you’ve described here:

    My understanding was, this allows you to load fonts ONLY when used.

    …is actually the default browser behaviour for @font-face. If you have 10 @font-face declarations, but only used one corresponding font-family on the page, only one of the font files will be loaded.

    Font Face Observer is great when you want to do something else once a font is available, ex. use it on a canvas, apply a CSS class, etc. I think Font Face Observer will need to use the family to check if it’s available, so that would be why they are being loaded even if you haven’t used them anywhere else in your own CSS. If you don’t need to do anything else when the font has loaded, maybe the browser default behavior will work as-is for you.