A simple feature test for the WOFF2 font format.
woff2-feature-testGiven that we use loadCSS to asynchronously load a stylesheet containing all of our typefaces as data URIs, we need a way to programmatically determine if the WOFF2 format is supported in the browser.
var fontFile = "/url/to/woff.css";
// Use WOFF2 if supported
if( supportsWoff2 ) {
fontFile = "/url/to/woff2.css";
}
loadCSS( fontFile );
We use the Font Loading API to load an empty WOFF2 data URI and see if the font set status is loading or not. If it attempts to load, the format is supported. If it does not, the format is unrecognized (see the intentionally failing test with an imaginary format).
If a browser eventually implements the WOFF2 format but does not implement the Font Loading API, this script will report a false negative (which is preferable to the false positive scenarios described above).
Note that if you use a restrictive Content Security Policy header on font-src, that can cause issues with this feature test.
You’ll also need to make sure your Content Security Policy allows Data URIs.
For example, github.com (not github.io) uses Content-Security-Policy:default-src *; font-src assets-cdn.github.com; which denies our @font-face Data URI.
A few previous revisions of this script can be found on a gist.