Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is it possible to load an external font via inline CSS?

Note: I'm not talking about using an external CSS file with a @font-face definition, but rather something like the following:

<h1 style="font-family:myfont;
    src:('http://example.com/font/myfont.tff')">test</h1>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
230 views
Welcome To Ask or Share your Answers For Others

1 Answer

Is it possible loading an external font with inline css? NOT with an external CSS file [....].

Yes, you can base64 encode a font or fonts as shown in this article from Stephen Scaff and drop them into a style block in your page to avoid the external request.

It may also be possible to use this technique in the way you describe if the browser you're using supports it.

<style>
  @font-face {
    font-family: 'PT Sans';
    font-style: normal;
    font-weight: normal;
    src: local('PT Sans'), local('PTSans-Regular'),
      url(data:application/font-woff2;charset=utf-8;base64,d09GRgABAAAAAHowABMAAAAA+OAA) format('woff2');
  }
  @font-face {
    font-family: 'PT Serif';
    font-style: normal;
    font-weight: normal;
    src: local('PT Serif'), local('PTSerif-Regular'),
      url(data:application/font-woff2;charset=utf-8;base64,d09GRgABAAAAAIQYABMAAAAA/MAA) format('woff2');
  }
</style>

Every modern browser supports WOFF2, so you should probably use that and only that for the foreseeable future. Also, this technique will improve your page speed scores, but will degrade performance overall (even for first page loads), unless you're only base64-encoding critical page assets (e.g. glyphs of the font shown above the fold) and asynchronously load the rest.

Performance-wise your best bet right now is to use Brotli compression and pipe the webfont stylesheet down with HTTP/2 Server Push.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...