如何知道何时应用了字体 [英] How to know when font-face has been applied
问题描述
我目前正在为广泛使用自定义字体的客户建立公司网站.
I am currently building a corporate website for a customer that uses custom fonts extensively.
在支持jQuery DOM的jQuery上,我正在进行位置计算,以根据动态内容确定应将具有动态宽度和高度的某些弹出菜单放置在何处.
On jQuerys DOM-ready I am doing placement calculations to figure out where some pop-up menus with dynamic width and height should be placed based on their dynamic contents.
这些计算失败,因为在应用字体之前会启用DOM-ready,因此宽度和高度不正确.
These calculations fail, since DOM-ready is fired before font-face is applied, and thus widths and heights are incorrect.
现在(对于原型),我正在DOM准备就绪后500毫秒进行计算,以缓解此问题,但是由于明显的原因,该方法无法投入生产.
Right now (for the prototype) i am doing the calculations 500ms after DOM-ready to alleviate this problem, but this can't go into production for obvious reasons.
该问题已在最新的Firefox和chrome中发现. IE 8似乎没有问题,但是随后准备就绪的DOM触发时间很晚,所以延迟是一种内建的:)
The problem has been observed in latest Firefox and chrome. IE 8 doesn't seem to have the problem, but then DOM-ready fires fairly late, so the delay is kind of built in I guess :)
等待加载事件不是一种选择,所以我对您的问题是:
Waiting for the load event is not an option, so my question to you is this:
是否有可靠的跨浏览器方法来检测何时应用了字体?
Is there a reliable cross-browser way to detect when font-face has been applied?
推荐答案
我想知道IE为什么不会遭受此问题困扰后找到了解决方案.
I found a solution after wondering why IE doesn't suffer from this problem.
Firefox和Chrome/Safari在应用字体之前触发DOMContentLoaded
事件,从而引起问题.
Firefox and Chrome/Safari triggers the DOMContentLoaded
event before font-face is applied, thus causing the problem.
解决方案是不听DOMContentLoaded
,而是去老学校听onreadystatechange
,等到document.readyState === 'complete'
,它总是在应用了font-face之后触发(据我的测试可知) )-这当然是IE中经常发生的情况,因为它不支持DOMContentLoaded
.
The solution is to not listen for DOMContentLoaded
but instead go oldschool and listen to onreadystatechange
and wait until the document.readyState === 'complete'
which is always triggered after font-face is applied (as far as I can tell by my tests) - which is of course what always happens in IE since it doesn't support DOMContentLoaded
.
因此,基本上,您可以在jQuery中滚动自己的事件,称为fontfaceapplied
-也许应该内置;)
So basically you can roll-your-own event in jQuery called fontfaceapplied
- maybe it should be built in ;)
document.onreadystatechange = function() {
if (document.readyState === 'complete')
$(document).trigger('fontfaceapplied');
};
有趣的事实:Opera正确做到了 ,并等待触发DOMContentLoaded
,直到应用了字体为止.
Funny fact: Opera does it right and waits to trigger DOMContentLoaded
until font-face is applied.
这篇关于如何知道何时应用了字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!