Skip to content

Instantly share code, notes, and snippets.

@matthisamoto
Created May 30, 2014 17:21
Show Gist options
  • Save matthisamoto/4af0112b39ac2e321a2c to your computer and use it in GitHub Desktop.
Save matthisamoto/4af0112b39ac2e321a2c to your computer and use it in GitHub Desktop.
loadFonts - a sort-of hacky way to check if fonts have loaded
/*
loadFonts - a sort-of hacky way to check if fonts have loaded
"Forked" from this: http://stackoverflow.com/a/11689060
*/
function loadFonts (fonts, callback) {
var loadedFonts = 0, fontList = [], interval;
for(var i = 0, l = fonts.length; i < l; ++i) {
(function(font) {
var node = document.createElement('span');
node.id = "fontNode_" + i;
// Characters that vary significantly among different fonts
node.innerHTML = 'giItT1WQy@!-/#';
// Visible - so we can measure it - but not on the screen
node.style.position = 'absolute';
node.style.left = '-10000px';
node.style.top = '-10000px';
// Large font size makes even subtle changes obvious
node.style.fontSize = '300px';
// Reset any font properties
node.style.fontFamily = 'sans-serif';
node.style.fontVariant = 'normal';
node.style.fontStyle = 'normal';
node.style.fontWeight = 'normal';
node.style.letterSpacing = '0';
document.body.appendChild(node);
// Remember width with no applied web font
node.originalWidth = node.offsetWidth;
node.style.fontFamily = font;
fontList.push(node);
})(fonts[i]);
}
function checkFont() {
for(var i = 0, l = fontList.length; i < l; ++i) {
(function(node) {
node = document.getElementById(node.id);
// Compare current width with original width
if(node && node.offsetWidth != node.originalWidth) {
++loadedFonts;
node.parentNode.removeChild(node);
node = null;
}
// If all fonts have been loaded
if(loadedFonts >= fonts.length) {
if(interval) {
clearInterval(interval);
}
if(loadedFonts == fonts.length) {
callback();
return true;
}
}
})(fontList[i]);
}
};
if(!checkFont()) {
interval = setInterval(checkFont, 50);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment