WOFF2 See the Wizard, a Wonderful JavaScript Feature Test

We’re always interested in ways to lessen the weight of the assets we serve on sites, which often means better performance for all. Thankfully, newer browsers are starting to support the new WOFF2 compression format, the successor to the widely implemented WOFF font format. On average, WOFF2 results in 30% smaller files compared to WOFF. A smaller font file means a shorter Flash of Invisible Text (FOIT) so we want to use WOFF2 over WOFF where we can.

It’s simple to specify the WOFF2 font source first in your @font-face rules. Browsers that support WOFF2 will benefit from the better compression and all others will download the more compatible, but larger, WOFF font file.

@font-face {
    font-family: CoolFont;
        url('coolfont.woff2') format('woff2'),
        url('coolfont.woff') format('woff');

A benefit of using WOFF2 is that it can minimize the impact of the FOIT, which renders your text invisible until the font is fully loaded. Reducing the font weight with WOFF2 reduces the amount of time required to load the font, which reduces FOIT times.

At Filament Group, we aren’t satisfied with simply minimizing the impact of FOIT. We eliminate FOIT using loadCSS, asynchronously loading a stylesheet containing all of our typefaces as data URIs. This minimizes the number of requests and avoids the dreaded FOIT by showing the native fallback font while the custom fonts load in the background.

However, this method requires that we know if a format is supported before we make the CSS request—we wouldn’t want to request a CSS stylesheet full of WOFF2 Data URIs in a browser that didn’t support WOFF2. So to use WOFF2 with loadCSS, we need a reliable feature test for WOFF2 support so we can do something like this:

var fontFile = "/url/to/woff.css";

// Use WOFF2 if supported
if( supportsWoff2 ) {
	fontFile = "/url/to/woff2.css";

loadCSS( fontFile );

Unfortunately, existing feature test libraries (like Modernizr) don’t contain individual tests for specific font formats like WOFF2. This is understandable because it’s more common to use the list of remote font format URLs and let the browser decide which to download.

With that in mind, we set out to create our own standalone (vanilla) JavaScript feature test for WOFF2 support. The final WOFF2 feature test script we created is only 198 bytes (after GZIP) and has very little performance overhead so this seems like a good tradeoff to gain a 30% savings in file size. On a recent client project we were able to save ~15KB after GZIP for browsers that support WOFF2. We thought others might find this feature test useful, so we’ve decided to release it as an open source project.

Article title credit to John Bender.

All blog posts