字体加载优化
Published on February 5, 2024Updated on March 23, 2024
首屏加载中的 FOUC(Flash of Unstyled Content) 是需要极力避免的,为此我们常常将关键路径使用的样式内联到 HTML 中。 同样的,字体文件在加载完成之前,浏览器会使用缺省字体显示内容,这就是 FOUT(Flash of Unstyled Text)。 但是问题就出在这里,除了 IE,其他浏览器都会等待 3 秒才展示系统字体,这就造成了 3 秒的 FOIT(Flash of Invisible Text)。用户不得不面对长达 3 秒消失了文字的内容。
使用 font-display: swap; 来解决
CSS@font-face { font-family: Lato; src: url('font-lato/lato-regular-webfont.woff2') format('woff2'), url('font-lato/lato-regular-webfont.woff') format('woff'); font-display: swap; }
看 caniuse 的数据兼容性还可以 https://caniuse.com/?search=font-display%3A%20swap
https://css-tricks.com/almanac/properties/f/font-display/ 通过设置 font-display: swap; 告诉浏览器在字体没有下载下来时,先使用 fallback font
参考
关于字体加载优化更多可以看看