Skip to content

Instantly share code, notes, and snippets.

@eugeneglova
Created November 17, 2014 12:24
Show Gist options
  • Save eugeneglova/dac94bbd1b0347efa440 to your computer and use it in GitHub Desktop.
Save eugeneglova/dac94bbd1b0347efa440 to your computer and use it in GitHub Desktop.
Web Font Loader
(function() {
"use strict";
var loaded_css_urls = [];
function getFontById(fonts, id) {
var found_font;
fonts.some(function(font) {
if (font.id === id) {
found_font = font.default_variation;
return true;
} else {
font.variations.some(function(variation) {
if (variation.id === id) {
found_font = variation;
// Fix variation css.url null value
found_font.css.url = font.css.url;
return true;
}
}, this);
}
}, this);
return found_font;
}
function loadFont(css_font_family, css_url, callback, callback_context) {
var options = {
custom: {
families: [css_font_family],
urls: [],
},
fontactive: $.proxy(callback, callback_context)
};
// Do not load the same url twice
if (loaded_css_urls.indexOf(css_url) !== -1 || $("link[href='" + css_url + "']").length) {
css_url = null;
} else {
loaded_css_urls.push(css_url);
}
// Load css only for valid urls
if (css_url && css_url.length) {
options.custom.urls.push(css_url);
}
WebFont.load(options);
}
// Getting fonts from WFP API
WFP.getFonts(function(fonts, err) {
var font_id = "eyJpZCI6MTE2MzgsInNvdXJjZSI6Im5hdGl2ZSJ9";
if (err) {
console.log("Failed to get fonts");
return false;
}
// Search font object by font id
var font = getFontById(fonts, font_id);
if ( ! font) {
console.log("Failed to get font by id", font_id);
return false;
}
loadFont(font.css.font_family, font.css.url, function() {
console.log("Applying font-family", font.css.font_family);
// Apply loaded font family to the element
$("body").css("font-family", font.css.font_family);
}, this);
}, this);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment