Improved Web Font Loading with Font Events API

Last year when I created this site, I set out with the goal of performance as my top priority. Recently, I’ve noticed the dreaded “Flash of Invisible Text” (FOIT) when using certain browsers. I ran across Scott Jehl’s article Font Loading Revisited with Font Events and decided to take his approach for a spin.

In the article, Scott mentions a few Font Load Event API polyfills. For my approach, I’m using Bram Stein’s FontFaceObserver script.

var OpenSans300 = new FontFaceObserver("Open Sans", { weight: 300 });
var OpenSans400 = new FontFaceObserver("Open Sans", { weight: 400 });
var OpenSans700 = new FontFaceObserver("Open Sans", { weight: 700 });

Promise.all([
  OpenSans300.check(),
  OpenSans400.check(),
  OpenSans700.check()
]).then(function() {
  document.documentElement.className += " fonts-loaded";
});
body {
  font-family: sans-serif;
}
.fonts-loaded body {
  font-family: 'Open Sans', sans-serif;
}

I tested with WebPageTest in Chrome using a 3G connection from the Dulles, VA location. Here are the before and after results:

Before: Web font loading with FOIT

Here, on the slower 3G connection, you can clearly see the FOIT in the middle frames before the web font is loaded and rendered in the final frame.

After: Improved web font loading without FOIT

The web font is still rendered in the final frame but now the FOIT is all gone!