Google 的 Web Fonts API 提供了一种方法来定义要在字体完成加载或无法加载等情况下执行的回调函数。有没有办法使用 CSS3 网络字体(@font-face)实现类似的功能?
5 回答
2015 更新
Chrome 35+ 和 Firefox 41+ 实现了CSS 字体加载 API ( MDN , W3C )。调用document.fonts
获取一个FontFaceSet对象,该对象具有一些用于检测字体加载状态的有用 API:
check(fontSpec)
- 返回给定字体列表中的所有字体是否已加载且可用。字体使用CSS 速记语法fontSpec
。例子: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 或支持库:
- Web Font Loader - 由 Google 和 Adob e 开发
- FontFaceOnload - 与 Web Font Loader 类似的更轻量级的方法
- FontLoader - polyfill
在 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
});
Google Web Fonts API(和 Typekit)使用的 JS 库可以在没有服务的情况下使用:WebFont Loader。
它定义了您所要求的回调,以及更多。
2017 更新
JS 库FontFaceObserver绝对是截至 2017 年最好、最轻量级的跨浏览器解决方案。它还公开了一个基于 Promise 的.load()
接口。
window.load 事件将在所有内容加载后触发 - 这应该包括字体所以您可以将其用作回调。但是,我认为您不必决定将网络字体加载器用作
除了 google、typekit、ascerder 和 monotype 选项之外,还有一个自定义模块可以从任何网络字体提供商加载样式表。
WebFontConfig = { 自定义:{ 系列:['OneFont','AnotherFont'],网址:['http://myotherwebfontprovider.com/stylesheet1.css','http://yetanotherwebfontprovider.com/stylesheet2.css']} };
无论您指定哪个提供者,库都会发送相同的事件。