Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Load CSS `@font-face` fonts by listening for font loading events. A workaround while we wait for browsers to support the `font-rendering: swap` property.
/*
Font activation on load based on code from:
http://www.filamentgroup.com/lab/font-events.html (Copyright (c) 2015 Filament Group)
Dependencies:
- FontFaceObserver https://github.com/bramstein/fontfaceobserver
- Cookie function https://github.com/filamentgroup/cookie
For the best performance and experience, add the `activeClass`
class to the `<html>` element on the server side after checking
for the presence of the `activeCookie` cookie.
*/
(function (w) {
'use strict';
var fonts = {
'Lato': [
{ 'weight': 300 },
{ 'weight': 300, 'style': 'italic' },
{ 'weight': 700 }
],
'Gibson': [
{ 'weight': 700 }
]
},
activeClass = 'webfonts-active',
activeCookie = 'webfonts-cached',
observers = [];
// hasClass polyfill from http://youmightnotneedjquery.com/#has_class
function hasClass(el, className) {
if (el.classList) {
return el.classList.contains(className);
}
return new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
}
// if the class is already set, we're good.
if (hasClass(w.document.documentElement, activeClass)) {
return;
}
function activate() {
// add a class to the document indicating the fonts have loaded
w.document.documentElement.className += ' ' + activeClass;
// set a cookie to optimise future visits
cookie(activeCookie, 'true', 7);
}
// if the fonts have already been downloaded, activate them
// (this becomes redundant once `activeCookie` presence is
// detected on the server side)
if (cookie(activeCookie)) {
activate();
return;
}
// activate & fail if we do not have FontFaceObserver, Promise, or ECMAScript 5
if (!('FontFaceObserver' in w) || !('Promise' in w) || !('keys' in Object)) {
activate();
return;
}
Object.keys(fonts).forEach(function (fontFamily) {
fonts[fontFamily].forEach(function (fontProperties) {
var new_observer = new w.FontFaceObserver(fontFamily, fontProperties);
observers.push(new_observer.check());
});
});
w.Promise
.all(observers)
.then(activate());
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment