Loading an external font via inline CSS

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.

Leave a Comment