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

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

问题描述

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



注意: 并不是谈论使用外部CSS文件使用 @ font-face 定义,而是如下所示:

 < h1 style =font-family:myfont; 
src:('http://example.com/font/myfont.tff')> test< / h1>


解决方案


一个外部字体与内联的CSS?没有外部CSS文件[....]。

是的,你可以base64编码一种字体或字体,如<来自SoSweet Creative的这篇文章将它们放入 style 在您的页面中阻止,以避免外部请求。

也可能以您描述的方式使用此技术如果您使用的浏览器支持它。

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

每个现代浏览器支持WOFF2 ,所以你应该在可预见的将来使用。此外,这种技术会提高您的页面速度分数,但是会降低整体性能(即使是首页加载),除非您只有base64编码的关键页面资产(例如上面显示的字体的字形现在你最好的选择就是使用 brotlirel =nofollow noreferrer> Brotli压缩,然后用 HTTP / 2 Server Push


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>

解决方案

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 SoSweet Creative 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-woff;charset=utf-8;base64,d09GRgABAAAAAHowABMAAAAA+OAA) format('woff');
  }
  @font-face {
    font-family: 'PT Serif';
    font-style: normal;
    font-weight: normal;
    src: local('PT Serif'), local('PTSerif-Regular'),
      url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAIQYABMAAAAA/MAA) format('woff');
  }
</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 async loading 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.

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

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