问题描述
Google的Web Fonts API提供了一种定义回调函数的方法,如果字体加载完毕,或者无法加载等等,是否可以使用CSS3网络字体(@ font-face)实现类似的功能?
Google's Web Fonts API offers a way to define callback functions to be executed if a font has finished loading, or couldn't be loaded etc. Is there a way to achieve something similar using CSS3 web fonts (@font-face)?
推荐答案
2015年更新
Chrome 35+和Firefox 41+实施 CSS字体加载API (,)。调用 document.fonts
获取对象,它有一些用于检测字体加载状态的有用API:
2015 Update
Chrome 35+ and Firefox 41+ implement the CSS font loading API (MDN, W3C). Call document.fonts
to get a FontFaceSet object, which has a few useful APIs for detecting the load status of fonts:
- - 返回给定字体列表中的所有字体是否已加载且可用。
fontSpec
使用。例如:document.fonts.check('bold 16px Roboto'); // true或false
- - 返回表示字体加载和布局操作已完成。
示例:document.fonts .ready.then(function(){/ * ...所有字体加载... * /});
check(fontSpec)
- returns whether all fonts in the given font list have been loaded and are available. ThefontSpec
uses the CSS shorthand syntax for fonts.
Example:document.fonts.check('bold 16px Roboto'); // true or false
document.fonts.ready
- returns a Promise indicating that font loading and layout operations are done.
Example:document.fonts.ready.then(function () { /*... all fonts loaded...*/ });
这是一个显示这些API的代码段,另外还有 document.fonts.onloadingdone
,它提供了有关字体面的额外信息。
Here's a snippet showing these APIs, plus document.fonts.onloadingdone
, which offers extra information about the font faces.
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或支持库:
IE 11 doesn't support the API. Look at available polyfills or support libraries if you need to support IE:
- - 由Google和Adobe开发
- - 类似于Web Font Loader的方法
- - polyfill
- Web Font Loader - developed by Google and Adobe
- FontFaceOnload - lighter, similar approach to Web Font Loader
- FontLoader - polyfill
这篇关于加载Web字体后如何通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!