waitfont.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // http://stackoverflow.com/questions/4383226/using-jquery-to-know-when-font-face-fonts-are-loaded
  2. (function(){
  3. function waitForWebfonts(fonts, callback) {
  4. var loadedFonts = 0;
  5. for(var i = 0, l = fonts.length; i < l; ++i) {
  6. (function(font) {
  7. var node = document.createElement('span');
  8. // Characters that vary significantly among different fonts
  9. node.innerHTML = 'giItT1WQy@!-/#';
  10. // Visible - so we can measure it - but not on the screen
  11. node.style.position = 'absolute';
  12. node.style.left = '-10000px';
  13. node.style.top = '-10000px';
  14. // Large font size makes even subtle changes obvious
  15. node.style.fontSize = '300px';
  16. // Reset any font properties
  17. node.style.fontFamily = 'sans-serif';
  18. node.style.fontVariant = 'normal';
  19. node.style.fontStyle = 'normal';
  20. node.style.fontWeight = 'normal';
  21. node.style.letterSpacing = '0';
  22. document.body.appendChild(node);
  23. // Remember width with no applied web font
  24. var width = node.offsetWidth;
  25. node.style.fontFamily = font;
  26. var interval;
  27. function checkFont() {
  28. // Compare current width with original width
  29. if(node && node.offsetWidth != width) {
  30. ++loadedFonts;
  31. node.parentNode.removeChild(node);
  32. node = null;
  33. }
  34. // If all fonts have been loaded
  35. if(loadedFonts >= fonts.length) {
  36. if(interval) {
  37. clearInterval(interval);
  38. }
  39. if(loadedFonts == fonts.length) {
  40. callback();
  41. return true;
  42. }
  43. }
  44. };
  45. if(!checkFont()) {
  46. interval = setInterval(checkFont, 50);
  47. }
  48. })(fonts[i]);
  49. }
  50. }
  51. window.waitForWebfonts = waitForWebfonts;
  52. })();