Dan*_*ner 51 javascript webfonts
Google的Web Fonts API提供了一种定义回调函数的方法,如果字体加载完毕或无法加载等等,是否可以使用CSS3 Web字体(@ font-face)实现类似的功能?
Dan*_*scu 86
Chrome 35+和Firefox 41+实现了CSS字体加载API(MDN,W3C).调用document.fonts获取FontFaceSet对象,该对象有一些用于检测字体加载状态的有用API:
check(fontSpec) - 返回给定字体列表中的所有字体是否已加载且可用.在fontSpec使用的字体CSS缩写语法.document.fonts.check('bold 16px Roboto'); // true or falsedocument.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');
};Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
IE 11不支持API.如果需要支持IE,请查看可用的polyfill或支持库:
Tho*_*hem 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]);
}
};
Run Code Online (Sandbox Code Playgroud)
使用它像:
waitForWebfonts(['MyFont1', 'MyFont2'], function() {
// Will be called as soon as ALL specified fonts are available
});
Run Code Online (Sandbox Code Playgroud)