Preloading @font-face fonts?

前端 未结 13 1853
时光说笑
时光说笑 2020-12-04 11:13

Is it possible to preload or otherwise cache @font-face fonts, most likely with javascript, before the page loads so you don\'t get that ugly jump when the page finally does

13条回答
  •  既然无缘
    2020-12-04 11:34

    As I found the best way is doing is preloading a stylesheet that contains the font face, and then let browser to load it automatically. I used the font-face in other locations (in the html page), but then I could observe the font changing effect briefly.

    
    

    then in the font.css file, specify as following.

    @font-face {
      font-family: 'Open Sans';
      font-style: normal;
      font-weight: 400;
      src: local('Open Sans Regular'), local('OpenSans-Regular'),
           url('open-sans-v16-latin-regular.woff2') format('woff2'); /*  Super Modern Browsers */
    }
    

    You can't assign a name to fonts when it's preloaded through link tag (correct me if I was wrong I couldn't find a way yet), and thus you have to use font-face to assign the name to the font. Even though it's possible to load a font through link tag, it's not recommended as you can't assign a name to the font with it. Without a name as with font-face, you won't be able to use it anywhere in the web page. According to gtmetrix, style sheet loads at the beginning, then rest of the scripts/style by order, then the font before dom is loaded, and therefore you don't see font changing effect.

提交回复
热议问题