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

前端 未结 7 2087
日久生厌
日久生厌 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 09:16

    I got the same problem. And somehow i can't get Google webfont loader to work with ttf font (especially chinese fonts) or send a jquery response when font is loaded.

    So I came up with this a more basic solution, useful when changing font dynamically after page is loaded. it shows when the font face is properly loaded.

    First i create a dummy div and then fill it with 'abcd' and then give it a font size 40, record the width of the div. When the 'change font' event is invoked via a button or anything, it should track the dummy div width changes. Width changes would represent that the font has change.

    HTML CODE

    
    
    abdc

    JQuery

    //create a variable to track initial width of default font
    var trackwidth
    
    //when change font is invoke
    function changefont(newfont)
    {
       //reset dummy font style
        $('#dummy').css('font-family','initial !important;');
        $('#dummy').css({'font-size':'40px'});
        $('#dummy').html('abcd');
    
        //ensure that trackwidth is only recorded once of the default font
        if(trackwidth==null)
        {
           trackwidth=( $('#dummy').width());
        }
    
        //apply new font
        $('#dummy').css('font-family',newfont);
        checkwidth()
    }
    
    function checkwidth()
    {
       //check if div width changed
       if($('#dummy').width() == trackwidth)
        {
            //if div never change, detect again every 500 milisecs
            setTimeout(checkwidth, 500);
        }
        else
        {
          //do something, font is loaded!
        }
    }
    

提交回复
热议问题