Skip to content

Instantly share code, notes, and snippets.

@gmac
Last active November 3, 2016 20:46
Show Gist options
  • Save gmac/e4600ab3a6b096854a47b4f394c3420f to your computer and use it in GitHub Desktop.
Save gmac/e4600ab3a6b096854a47b4f394c3420f to your computer and use it in GitHub Desktop.
import Initializer from 'presto/initializer';
var $loaded = $.Deferred();
Initializer.registerComponent('site/font_loader', function(element, data) {
const STORAGE_NS = 'chorus-fonts-'+ data.version;
const FONTS_LOADED = ' fonts-loaded';
const SUCCESS = function() {};
var FontFaceObserver = require('./scripts/vendor/fontfaceobserver');
var storage = require('lib/localstorage');
var docEl = document.documentElement;
var fontPromises = data.catalog.map(function(def) {
// Add a check to the array of promises. The 10000 here is in reference to
// how many miliseconds to wait until we mark a font as failed. Note: This
// is long right now because we can have a pretty long deley for them to
// show up. We probably want to make this a little shorter later on, so
// there is no sudden switch once a user is already reading an article.
return new FontFaceObserver(def.family, def).load(null, 10000).then(SUCCESS, function() {
console.log('Font failure: '+JSON.stringify(def));
});
}, {
load: function() {
return $loaded.promise();
}
});
// Watch all the promises, so that they may be fulfilled.
Promise.all(fontPromises).then(function() {
// SUCCESS:
// mark fonts as loaded (triggering their display),
// then cache a flag noting that the user has successfully loaded fonts for the site.
// The inline loader script will expedite the display of fonts on subsequent pages.
docEl.className += FONTS_LOADED;
storage.set(STORAGE_NS, 'yes');
$loaded.resolve()
}, function() {
// FAILURE
// mark fonts as loaded (triggering the display of what fonts did successfully load),
// then cache a flag noting that fonts failed to load, and should be reattempted.
docEl.className += FONTS_LOADED;
storage.set(STORAGE_NS, 'no');
$loaded.reject()
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment