Created
October 15, 2013 13:34
-
-
Save lutzissler/6991628 to your computer and use it in GitHub Desktop.
Fire a callback when all provided webfonts have been loaded. Based on work by Thomas Bachem (http://stackoverflow.com/questions/4383226/using-jquery-to-know-when-font-face-fonts-are-loaded#11689060).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function waitForWebfonts(fonts, callback) { | |
| var loadedFonts = 0; | |
| for(var i = 0, l = fonts.length; i < l; ++i) { | |
| (function(font) { | |
| var node = document.createElement('span'); | |
| // 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 | |
| var width = node.offsetWidth; | |
| node.style.fontFamily = font; | |
| function checkFont() { | |
| // Compare current width with original width | |
| if(node && node.offsetWidth != width) { | |
| loadedFonts = loadedFonts + 1; | |
| node.parentNode.removeChild(node); | |
| node = null; | |
| } else { | |
| setTimeout(checkFont, 50); | |
| } | |
| }; | |
| checkFont(); | |
| })(fonts[i]); | |
| } | |
| // Wait | |
| function checkFonts() { | |
| // If all fonts have been loaded | |
| if(loadedFonts == fonts.length) { | |
| callback(); | |
| return; | |
| } | |
| setTimeout(checkFonts, 50); | |
| } | |
| checkFonts(); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment