字体显示方案

此文系读 font-display 后感,原发在 issues blog 里面。

浏览器默认方案

浏览器加载字体完成之前,文本默认是不显示的,这种情况通常叫做 FOIT。这种方案的好处是不会经历一个 fallback 字体 -> 指定字体的一个跳转,缺点是在网络差的情况下会有一段时间的空白。默认情况下大多数浏览器会等 3 秒钟,如果 3 秒钟之后还是渲染不出来就转而选择 fallback 字体,其中 safari 可能会等得更久,在没有网络的情况下,文本压根就不渲染了(因为字体加载不出来)。具体浏览器是怎么弄的,参考 Differences in Font Rendering Today

在指定字体加载完成前用 fallback 字体

先为相应的元素设置字体:

p {
  font-family: "Arial", "Helvetica", sans-serif;
}

.font-loaded p {
  font-family: "Open Sans Regular";
}

然后用 fontfaceobserver 监听字体加载,在加载完成的时候可以为相应的元素添加 class:

const font = new FontFaceObserver('Open Sans Regular');
const p = document.querySelector('p')
font.load().then(function () {
  p.classList.add('font-loaded')
})

新的 CSS 解决方案

@font-face {
  font-family: "Open Sans Regular";
  font-weight: 400;
  font-style: normal;
  src: url("fonts/OpenSans-Regular-BasicLatin.woff2") format("woff2");
  font-display: swap;
}
  • auto: The default value. The typical browser font loading behavior will take place, which is to hide typefaces that use custom fonts, and then display the affected text when fonts finish loading.

  • swap: The fallback text is shown immediately until the custom font loads. In most cases, this is what we’re after. JavaScript-driven font loading solutions almost always aim to emulate this setting.

  • fallback: This is sort of a compromise between auto and swap. There will be a short period of time (100ms according to Google) that text styled with custom fonts will be invisible. The unstyled text will then appear (if the custom font hasn’t already loaded by this point.) Once the font loads, the text is styled appropriately.

  • optional: Operates exactly like fallback in that the affected text will initially be invisible for a short period of time, and then transition to a fallback font. The similarities end there, though. The optional setting gives the browser freedom to decide whether or not a font should even be used, and this behavior hinges on the user’s connection speed. On slow connections, you can expect that custom fonts may not load at all if this setting is used.

相关阅读

    原文作者:陈屹峤
    原文地址: https://segmentfault.com/a/1190000006664033
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞