加载Web字体后如何通知

时间:2011-04-15 16:59:38

标签: javascript webfonts

谷歌的Web Fonts API提供了一种定义回调函数的方法,如果字体加载完毕,或者无法加载等,可以执行回调函数。有没有办法使用CSS3 web字体实现类似的东西(@ font-face) ?

5 个答案:

答案 0 :(得分:71)

2015年更新

Chrome 35+和Firefox 41+实施 CSS字体加载API MDNW3C)。调用document.fonts获取FontFaceSet对象,该对象有一些用于检测字体加载状态的有用API:

  • check(fontSpec) - 返回给定字体列表中的所有字体是否已加载且可用。 fontSpec使用CSS shorthand syntax for fonts。例如:document.fonts.check('bold 16px Roboto'); // true or false
  • document.fonts.ready - 返回Promise,表示已完成字体加载和布局操作。例如:document.fonts.ready.then(function () { /*... all fonts loaded...*/ });

以下是显示这些API的代码段以及document.fonts.onloadingdone,其中提供了有关字体外观的额外信息。

alert('Roboto loaded? ' + document.fonts.check('1em Roboto'));  // false

document.fonts.ready.then(function () {
  alert('All fonts in use by visible text have loaded.');
   alert('Roboto loaded? ' + document.fonts.check('1em Roboto'));  // true
});

document.fonts.onloadingdone = function (fontFaceSetEvent) {
   alert('onloadingdone we have ' + fontFaceSetEvent.fontfaces.length + ' font faces loaded');
};
<link href='https://fonts.googleapis.com/css?family=Roboto:400,700' rel='stylesheet' type='text/css'>
<p style="font-family: Roboto">
  We need some text using the font, for the font to be loaded.
  So far one font face was loaded.
  Let's add some <strong>strong</strong> text to trigger loading the second one,
    with weight: 700.
</p>

IE 11不支持API。如果需要支持IE,请查看可用的polyfill或支持库:

答案 1 :(得分:16)

在Safari,Chrome,Firefox,Opera,IE7,IE8,IE9中测试:

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;

            var interval;
            function checkFont() {
                // Compare current width with original width
                if(node && node.offsetWidth != width) {
                    ++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;
                    }
                }
            };

            if(!checkFont()) {
                interval = setInterval(checkFont, 50);
            }
        })(fonts[i]);
    }
};

使用它像:

waitForWebfonts(['MyFont1', 'MyFont2'], function() {
    // Will be called as soon as ALL specified fonts are available
});

答案 2 :(得分:11)

Google Web Fonts API(和Typekit)使用的JS库可以在没有服务的情况下使用:WebFont Loader

它定义了您要求的回调,以及many more

答案 3 :(得分:3)

2017年更新

JS库FontFaceObserver绝对是2017年最好,最轻量级的跨浏览器解决方案。它还公开了一个基于Promise的.load()界面。

答案 4 :(得分:-4)

当所有内容都加载时,window.load事件将会触发 - 应该包含字体 所以你可以用它作为回电。但是,我认为您不必决定使用Web字体加载器

  

除了google,typekit,   那里有ascender和monotype选项   也是一个可以加载的自定义模块   来自任何web字体的样式表   提供商。

     

WebFontConfig = {custom:{   家庭:['OneFont','AnotherFont'],       网址:['http://myotherwebfontprovider.com/stylesheet1.css',         'http://yetanotherwebfontprovider.com/stylesheet2.css'   ]}};

无论您指定哪个提供商,图书馆都会发送相同的事件。