Optimize the display of remote fonts: font-display property

When remote fonts are used in web pages, the font loading delay caused by network factors needs to be considered. Generally, there will be a gap: the document is loaded but the font file has not been loaded and parsed. How to plan the rendering of the text in the webpage during the gap? This uses an attribute: font-display.

Attribute introduction

This property specifies the document's presentation strategy when remote fonts are downloaded and available. If remote fonts are used in your website:

@ font-face {
  font-family: XXXX;
  src: url(/path/to/fonts/examplefont.woff)format('woff');
复制代码

There are three parts to the remote font rendering strategy:

  • Blocking period: Indicates that the browser will block the document to wait for the font to download. When the font cannot be loaded smoothly during the blocking period, the browser will use the alternate font
  • Swap period: When the font is loaded during the swap period, the candidate font rendered in the previous step needs to be replaced with the target font
  • Failure period: If the font cannot be downloaded within the above period, it will automatically adapt to the fallback font.

Here we focus on the first two. The combination of different durations of the blocking period and the exchange period corresponds to font-displaydifferent values ​​of the attributes:

  • block: Indicates that the document will be blocked for a period of time (approximately the blocking period 3s) to wait for 远程字体文件the download. If the font download is not completed within this time, the alternative font will be used, and the remote font will be downloaded before replacing it.
  • swap: Indicates that the document will not block(very short blocking period < 1s), use the alternative font directly, and replace the remote font after downloading.
  • fallback: Indicates that the document will not block(very short blocking period < 1s), use the alternative font directly, and replace the font after the download is completed within the exchange period (probably 2s), otherwise give up using the remote font.
  • optional: Indicates that the document will not block(very short blocking period < 1s), the font will be used after the font is loaded in such a short time, otherwise it will be abandoned.
  • auto: automatic mode, determined by the browser ( chromebehaves the swapsame as below)

Application Scenario Analysis

After analyzing the characteristics of the attribute, let's analyze its application scenarios.

如果想你的网站尽可能优先显示选用的字体,可以使用block属性值:它会block一段时间,等字体文件下载解析完毕再渲染文本,不会因生硬的字体切换带来不舒服的视觉体验。保证了文本视觉的一致性。

如果想你的网站尽可能保持文本可见,可以使用swap属性值:它会先用备选字体渲染文本,等你的字体加载好再替换。保证了文本的可见性。

还有一种情况就是所选的字体的缺席并不会带来很大的体验问题,换句话说:该字体并没有特别重要,那可以选择fallback值。不过这种场景不多。

一般情况下,swap的使用场景会更多一些。

总结

文本介绍了与远程字体相关的文本渲染,为了更好的观察这些值的区别,写了一个观察工具:font-display-testing ,可通过设置字体文件的加载延时和不同的font-display来理解这些值的区别: h8okn-hqrur.gif

Guess you like

Origin juejin.im/post/7078980464773595173