现在在GitHub上:https://github.com/patrickmarabeas/jQuery-FontSpy.js
基本上,该方法通过比较两种不同字体的字符串宽度来工作.我们使用Comic Sans作为测试的字体,因为它是最不同的网络安全字体,希望与您将使用的任何自定义字体都有足够的不同.此外,我们使用了非常大的字体大小,所以即使是很小的差异也会很明显.计算完Comic Sans字符串的宽度后,字体系列将更改为自定义字体,并返回Comic Sans.选中时,如果字符串元素宽度相同,则Comic Sans的备用字体仍在使用.如果没有,你的字体应该是可操作的.
I rewrote the method of font load detection into a jQuery plugin designed to give the developer the ability to style elements based upon whether the font has been loaded or not. A fail safe timer has been added so the user isn’t left without content if the custom font fails to load. That’s just bad usability.
通过添加和删除类,我还增加了对字体加载和失败时发生的事情的更大控制.你现在可以对字体做任何你喜欢的事情.我只建议修改字体大小、行距等,使您的回退字体尽可能接近自定义字体,以便您的布局保持完整,用户获得预期的体验.
Here's a demo: http://patrickmarabeas.github.io/jQuery-FontSpy.js
把下面的句子放到一个句子里.js文件并引用它.
(function($) {
$.fontSpy = function( element, conf ) {
var $element = $(element);
var defaults = {
font: $element.css("font-family"),
onLoad: '',
onFail: '',
testFont: 'Comic Sans MS',
testString: 'QW@HhsXJ',
delay: 50,
timeOut: 2500
};
var config = $.extend( defaults, conf );
var tester = document.createElement('span');
tester.style.position = 'absolute';
tester.style.top = '-9999px';
tester.style.left = '-9999px';
tester.style.visibility = 'hidden';
tester.style.fontFamily = config.testFont;
tester.style.fontSize = '250px';
tester.innerHTML = config.testString;
document.body.appendChild(tester);
var fallbackFontWidth = tester.offsetWidth;
tester.style.fontFamily = config.font + ',' + config.testFont;
function checkFont() {
var loadedFontWidth = tester.offsetWidth;
if (fallbackFontWidth === loadedFontWidth){
if(config.timeOut < 0) {
$element.removeClass(config.onLoad);
$element.addClass(config.onFail);
console.log('failure');
}
else {
$element.addClass(config.onLoad);
setTimeout(checkFont, config.delay);
config.timeOut = config.timeOut - config.delay;
}
}
else {
$element.removeClass(config.onLoad);
}
}
checkFont();
};
$.fn.fontSpy = function(config) {
return this.each(function() {
if (undefined == $(this).data('fontSpy')) {
var plugin = new $.fontSpy(this, config);
$(this).data('fontSpy', plugin);
}
});
};
})(jQuery);
Apply it to your project
.bannerTextChecked {
font-family: "Lobster";
/* don't specify fallback font here, do this in onFail class */
}
$(document).ready(function() {
$('.bannerTextChecked').fontSpy({
onLoad: 'hideMe',
onFail: 'fontFail anotherClass'
});
});
Remove that FOUC!
.hideMe {
visibility: hidden !important;
}
.fontFail {
visibility: visible !important;
/* fall back font */
/* necessary styling so fallback font doesn't break your layout */
}
编辑:删除了兼容性,因为它不能正常工作,并且在不同版本中遇到了问题.这里可以找到一个黑客补丁:https://github.com/patrickmarabeas/jQuery-FontFaceSpy.js/issues/1