通过内联 CSS 加载外部字体 [英] Loading an external font via inline CSS

查看:21
本文介绍了通过内联 CSS 加载外部字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过内联 CSS 加载外部字体?

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

注意:我不是谈论使用带有 @font-face 定义的外部 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>

推荐答案

是否可以使用内联 css 加载外部字体?不使用外部 CSS 文件 [....].

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

是的,您可以对一种或多种字体进行 base64 编码,如 这篇文章 来自 Stephen Scaff 并将它们放入页面中的 style 块中以避免外部请求.

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>

每个现代浏览器都支持 WOFF2,因此您可能应该使用它并且仅使用它 在可预见的未来.此外,这种技术将提高您的页面速度得分,但会降低整体性能(即使是第一页加载),除非您只是对关键页面资产进行 base64 编码(例如上面显示的字体的字形)折叠)和异步加载其余部分.

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.

就性能而言,您现在最好的选择是使用 Brotli 压缩,并使用HTTP/2 服务器推送.

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

这篇关于通过内联 CSS 加载外部字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆