Using jQuery to know when @font-face fonts are loaded?

前端 未结 7 2091
日久生厌
日久生厌 2020-11-28 08:35

I am using @font-face and I hate that Firefox shows the default font, waits to load the @font-face font, then replaces it. So the whole page flashes with the new font.

7条回答
  •  生来不讨喜
    2020-11-28 08:55

    I use google web fonts (Crete Round Regular and Open Sans Regular with Bold)

    You can use either this :

    var fonts = $.Deferred();
    WebFontConfig = { google: { families: [ 'Crete+Round::latin', 'Open+Sans:400,700:latin' ] } , active : function() { fonts.resolve(); } };
    (function() {
        var wf = document.createElement('script');
        wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
        wf.type = 'text/javascript';
        wf.async = 'true';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(wf, s);
    })();
    fonts.done(function(){ alert('fonts'); });
    

    or this :

    WebFontConfig = { google: { families: [ 'Crete+Round::latin', 'Open+Sans:400,700:latin' ] } , active : function() { alert('fonts'); } };
    (function() {
        var wf = document.createElement('script');
        wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
        wf.type = 'text/javascript';
        wf.async = 'true';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(wf, s);
    })();
    

    Note that in the first option i used jQuery Deferred Object.

提交回复
热议问题