How to know when font-face has been applied

扶醉桌前 提交于 2019-11-28 16:06:27
Martin Jespersen

I found a solution after wondering why IE doesn't suffer from this problem.

Firefox and Chrome/Safari triggers the DOMContentLoaded event before font-face is applied, thus causing the problem.

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.

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');
};

Funny fact: Opera does it right and waits to trigger DOMContentLoaded until font-face is applied.

Setting the function to trigger after a timeout of 200ms solves this issue when using Google Fonts.

There's a noticeable jump, but there usually is for equal heights stuff, for the purists this might not be perfect but it works cross browser.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!