网页字体加载
by Mattia Astorino
通过Mattia Astorino
Custom web fonts are used everywhere around the world, but many (oh so many) sites load them improperly. This causes a lot of problems for page loading like performance issues, slow loading time, blocked rendering and swapped fonts during navigation.
自定义Web字体在世界各地都可以使用,但是许多(哦,如此之多)网站无法正确加载它们。 这会导致很多页面加载问题,例如性能问题,加载速度慢,渲染过程受阻以及导航过程中字体交换。
I see many developers ignoring these issues or perhaps making the same errors over and over just because “they have always done so”, but as web developers we need to be able to adapt in a constantly changing environment.
我看到许多开发人员忽略了这些问题,或者仅仅因为“他们一直这样做”而一再犯同样的错误,但是作为Web开发人员,我们需要能够适应不断变化的环境。
It’s time to break this loop and start doing the right thing in 2019. There are just four steps to consider when loading a custom web font:
现在是时候打破这种循环并在2019年开始做正确的事情了。加载自定义Web字体时只需考虑四个步骤:
- Use the correct font format 使用正确的字体格式
- Preload fonts 预加载字体
- Use the correct font-face declaration 使用正确的字体声明
- Avoid invisible text during font loading. 避免在字体加载期间显示不可见的文本。
Let’s break down these points one at a time.
让我们一次分解这些要点。
使用正确的字体格式 (Use the correct font format)
There are many font formats that can be used on the web, but only two formats are really needed if you don’t have to support Internet Explorer (IE) 8 or lower: woff and woff2. These are the only two file types you should use because they are compressed in the gzip format by default (so they are very small), are optimised for the web, and are fully supported by IE 9+ and all other evergreen browsers.
Web上可以使用许多字体格式,但是如果您不必支持Internet Explorer(IE)8或更低版本,则实际上仅需要两种格式: woff和woff2 。 这是您应该使用的仅有的两种文件类型,因为它们默认情况下以gzip格式压缩(因此非常小),针对Web进行了优化,并且受到IE 9+和所有其他常绿浏览器的完全支持。
预加载字体 (Preload fonts)
When using custom fonts you should tell the browser to preload them using the appropriate rel=""
tag and attributes:
使用自定义字体时,应告知浏览器使用相应的rel=""
标签和属性来预加载它们:
<link rel="preload" as="font" href="/fonts/custom-font.woff2" type="font/