web字体库加载优化_优化Web字体以提高性能:最新技术

作者:神秘网友 发布时间:2020-09-04 10:23:15

web字体库加载优化_优化Web字体以提高性能:最新技术

web字体库加载优化_优化Web字体以提高性能:最新技术

web字体库加载优化

This article is part of a series created in partnership with SiteGround. Thank you for supporting the partners who make SitePoint possible.

本文是与SiteGround合作创建的系列文章的一部分。 感谢您支持使SitePoint成为可能的合作伙伴。

67% of webpages now use custom fonts. However, popularity and widespread adoption haven’t come without some performance and user experience-related issues.

现在有67%的网页使用自定义字体 。 但是,没有一些性能和与用户体验相关的问题就不会实现普及和广泛采用。

In this article, I’ll go through what’s not so good about the way web fonts are commonly used and loaded, as well as point you to well-tested workarounds and future standards-based solutions.

在本文中,我将介绍Web字体的常用使用和加载方式的不好之处,并为您提供经过良好测试的变通办法和未来基于标准的解决方案。

Users come to your website for content. Therefore, great typography is crucial on the web: readability, legibility and well-crafted typographic design are a must for brand recognition and the success of your message.

用户访问您的网站以获得内容。 因此,出色的排版在网络上至关重要:可读性,易读性和精心设计的排版设计是品牌知名度和信息成功的必备条件。

The best way to achieve beautiful typography is by loading custom web fonts — that is, font files that are not already installed on users’ devices.

实现精美字体的最佳方法是加载自定义Web字体,即尚未在用户设备上安装的字体文件。

Since browser support for the CSS @font-face rule has become widespread, using custom web fonts in websites has increased by leaps and bounds. However, fonts can have a heavy file size, and loading extra resources on your website doesn’t come without some negative impact on performance.

由于浏览器对CSS @font-face规则的支持已得到广泛普及,因此在网站中使用自定义Web字体已得到了突飞猛进的发展。 但是,字体的文件大小可能很大,并且在网站上加载额外的资源不会对性能造成负面影响。

Since file size can certainly be an issue, paying attention to how custom web fonts are loaded comes to the forefront.

由于文件大小肯定是一个问题,因此要注意如何加载自定义Web字体。

The most common way of using a custom web font is to specify the fonts used inside a CSS @font-face declaration and leave the browser to its default behavior. This is not ideal. Since information about fonts is located in the CSS, by default browsers delay the loading of fonts until the CSS is parsed. That’s not all. As Zach Leatherman has made abundantly clear, to trigger a font download, a number of conditions must be met besides a valid @font-face declaration:

使用自定义Web字体的最常见方法是指定CSS @font-face声明中使用的@font-face ,并使浏览器保持其默认行为。 这是不理想的。 由于有关字体的信息位于CSS中,因此默认情况下,浏览器会延迟字体的加载,直到CSS被解析为止。 那不是全部。 正如Zach Leatherman明确指出的那样,要触发字体下载,除了有效的@font-face声明外,还必须满足许多条件:

  • an HTML node that uses the same font-family specified inside @font-face

    一个HTML节点,该节点使用@font-face指定的相同font-family

  • in Webkit and Blink browsers, that node must not be empty

    在Webkit和Blink浏览器中,该节点不能为空
  • in browsers that support the unicode range descriptor inside @font-face, the content must also match the specified unicode range.

    在支持 @font-face内unicode范围描述符的浏览器中 ,内容还必须与指定的unicode范围匹配。

If all the points above are satisfied, the browser starts downloading the font. This means that the browser needs to have parsed not only the CSS code but also a website’s text content before it can trigger a font’s download. However, it’s just when the font starts loading that web users are likely to experience the dreaded Flash Of Invisible Text, or FOIT for short.

如果满足以上所有条件,浏览器将开始下载字体。 这意味着浏览器不仅需要解析CSS代码,而且还必须解析网站的文本内容,才能触发字体的下载。 但是,只有在字体开始加载时,Web用户才可能会遇到可怕的Invisible Text闪光 (简称FOIT)

web字体库加载优化_优化Web字体以提高性能:最新技术

FOIT: Page at http://blog.instagram.com/ while fonts are loading on Firefox v.52. Text is invisible.

FOIT:http://blog.instagram.com/上的页面,而Firefox v.52上正在加载字体。 文字不可见。

web字体库加载优化_优化Web字体以提高性能:最新技术

FOIT: Page at http://blog.instagram.com/ after fonts have been loaded on Firefox v.52. Text has become visible.

FOIT:在Firefox v.52上加载字体后,请访问http://blog.instagram.com/页面。 文字已可见。

In other words, as soon as browsers start downloading a font, all text becomes invisible. So users look at a screen with no text for some time, which under sub-par network conditions can feel like forever. Furthermore, the way different browsers handle FOIT also varies:

换句话说,一旦浏览器开始下载字体,所有文本都将变为不可见。 因此,用户看屏幕一段时间后没有任何文字,在低于标准的网络条件下,感觉就像永远一样。 此外,不同浏览器处理FOIT的方式也有所不同:

  • Blink and Firefox browsers tackle FOIT by introducing a three-second timeout: the text disappears for up to three seconds during font loading. If the font hasn’t loaded within this time frame, the website displays a fallback font, which is subsequently replaced with the custom font once this is fully loaded. This behavior gives rise to what is known as FOUT (another acronym): Flash Of Unstyled Text.

    Blink和Firefox浏览器通过引入三秒钟的超时来解决FOIT:在字体加载过程中,文本最多消失三秒钟。 如果尚未在此时间段内加载字体,则网站会显示一个后备字体,该字体在完全加载后会被自定义字体替换。 此行为引起了所谓的FOUT (另一个缩写): Flash of Unstyled Text

  • Safari, the default Android Browser and Blackberry don’t use a timeout but display no text until the custom font is loaded. If anything goes wrong and the font doesn’t get loaded, users are left with invisible text on the screen.

    Safari,默认的Android浏览器和Blackberry不会使用超时,但在加载自定义字体之前不会显示任何文本。 如果出现任何问题并且没有加载字体,则会在屏幕上向用户显示不可见的文本。
  • IE/Edge browsers don’t hide text, but display the fallback font right away, which seems to be a better design decision by Microsoft.

    IE / Edge浏览器不会隐藏文本,而是立即显示后备字体,这似乎是Microsoft更好的设计决策。

Although having a sudden change in typeface when reading text on a website is not the best user experience, staring at a blank screen while the font is loading sounds much worse. Ideally, a working approach should overcome both FOUT and FOIT. However, although it’s an open issue, there is some consensus among a number of experts that FOUT is way better than FOIT.

虽然在网站上阅读文本时字体突然改变并不是最佳的用户体验,但是在加载字体时凝视空白屏幕听起来更糟。 理想情况下,一种可行的方法应该同时克服FOUT和FOIT。 但是,尽管这是一个未解决的问题,但许多专家已经达成共识,即FOUT比FOIT更好。

Tackling the issues related to loading fonts involves working both on optimizing the file size and taking control of the default browser behavior so as to eliminate FOIT and minimizing the jarring impact of FOUT.

解决与加载字体有关的问题涉及优化文件大小和控制默认浏览器行为,以消除FOIT并最大程度地降低FOUT的不利影响。

Let’s look closer into each task one at a time.

让我们一次仔细地研究每个任务。

There are a few steps you can take to make sure your font files are not super heavy.

您可以采取一些步骤来确保字体文件不会太沉重。

#1尽量减少项目中的字样数量 (#1 Minimize the number of typefaces in your project)

Don’t think that just because you can choose from tons of beautiful typefaces, you need to weigh down your website with a multitude of different fonts. The opposite is the case.

不要认为仅仅因为可以从大量漂亮的字体中进行选择,就需要使用多种不同的字体来权衡您的网站。 情况恰恰相反。

In most situations, a couple of judiciously paired typefaces can work wonders for your design and have a lighter impact on website performance.

在大多数情况下,几个明智地配对的字体可以为您的设计创造奇迹,并且对网站性能产生较小的影响。

#2提供基于浏览器支持的Web字体格式 (#2 Provide web font formats based on browser support)

There are four main font formats:

有四种主要的字体格式:

  • True Type Font (TTF), a common font format that’s been around since the late 80s

    True Type字体(TTF) ,一种常见的字体格式,自80年代末以来就存在

  • Web Open Font Format (WOFF), a format developed in 2009 which is Open Type or True Type, only with compression and further metadata

    Web开放字体格式(WOFF) ,2009年开发的一种格式,是Open Type或True Type,仅具有压缩和更多元数据

  • Web Open Font Format (WOFF2), a better compressed format than WOFF

    Web开放字体格式(WOFF2) ,比WOFF更好的压缩格式

  • Embedded Open Type (EOT), a format designed by Microsoft to be used for embedded fonts on the web.

    嵌入式开放类型(EOT) ,一种由Microsoft设计的格式,用于Web上的嵌入式字体。

Although you could specify all of them in your @font-face declaration, you can get away with just two of them. Here’s how:

尽管您可以在@font-face声明中指定所有它们,但是您可以仅删除其中两个。 这是如何做:

@font-face {
  font-family: 'Open Sans';
  src: local('Open Sans'), local('OpenSans'),
       url('fonts/open-sans.woff2') format('woff2'),
       url('fonts/open-sans.woff') format('woff');
}

The first format you suggest to the browser is woff2, which gives you the advantage of extra compression. If your browser doesn’t support woff2, it just selects woff, which has good compression and enjoys support by the latest versions of all major browsers. Only Opera Mini lacks support for it, together with IE8 and older Android Mobile browsers. If you use a progressive enhancement approach to web development, you could simply let these older browsers fall back on a system font, e.g., Arial, Verdana, etc.

建议浏览器使用的第一种格式是woff2,它为您提供了额外压缩的优势。 如果您的浏览器不支持woff2,它只会选择woff,它具有良好的压缩能力,并得到所有主要浏览器的最新版本的支持 。 仅Opera Mini,IE8和较旧的Android Mobile浏览器均不支持它。 如果您使用渐进式增强方法进行Web开发,则可以简单地让这些较旧的浏览器使用系统字体,例如Arial,Verdana等。

#3仅加载您需要的样式 (#3 Load just the styles you need)

Fonts usually have different variants — italic, bold, etc. Each font variation adds weight to the file size, so try to avoid adding a font variation to your @font-face code if you’re not going to use it on your website. Keep in mind that if you use an <i> tag to add an icon, which is quite common, that is enough to get the browser to load the italic font variant (Slide 77 in Zack Leatherman’s Santa Clara Velocity talk of 2015). If that’s the only instance of <i> in your page, using a <span> tag for the icon or setting the font-style for the <i> element to normal instead would spare the browser from having to download unnecessary resources.

字体通常具有不同的变体-斜体,粗体等。每种字体变体都会增加文件大小的权重,因此,如果您不想在网站上使用它,请避免在@font-face代码中添加字体变体。 请记住,如果使用<i>标签添加图标(这很常见),就足以使浏览器加载斜体字体变体( Zack Leatherman在2015年的Santa Clara Velocity演讲中的Slide 77 )。 如果这是页面中<i>的唯一实例,则对图标使用<span>标记,或者将<i>元素的font-style设置为normal将使浏览器不必下载不必要的资源。

#4降低角色设定 (#4 Keep your character sets down)

Avoid loading all the characters, numbers and symbols your chosen font makes available. Instead, select just the character sets you actually use on your webpage.

避免加载您选择的字体可用的所有字符,数字和符号。 而是只选择您在网页上实际使用的字符集。

You can learn everything about fonts subsetting in Slash Page Load Times With CSS Font Subsetting, by Dudley Storey.

您可以在Dudley Storey的“使用CSS字体子设置使用Slash页面加载时间”中了解有关字体子设置的所有信息。

Let’s look at some alternatives available today for dealing with FOIT. I’ve singled out the simplest approaches to implement among effective and recommended practices. However, you can learn about far more sophisticated ones in Zach Leatherman’s A Comprehensive Guide to Font Loading Strategies.

让我们看一下当今用于处理FOIT的一些替代方法。 我从有效和推荐的实践中挑选出最简单的方法来实施。 但是,您可以在Zach Leatherman的《字体加载策略综合指南》中了解更为复杂的内容。

不要使用自定义字体 (Don’t use custom fonts)

If you can’t stand the idea of your users staring at invisible text or at font-swapping shifts, the most simple option is to give up on custom fonts and rely solely on web-safe fonts.

如果您无法忍受用户盯着不可见的文本或字体转换,那么最简单的选择就是放弃自定义字体,而仅依靠网络安全字体。

These fonts are preinstalled on users’ devices, so the browser doesn’t need to load them. Even when deciding to use custom fonts, web safe-fonts are commonly added to the font stack as a fallback.

这些字体已预先安装在用户的设备上,因此浏览器不需要加载它们。 即使在决定使用自定义字体时,通常也会将Web安全字体作为后备添加到字体堆栈中。

Giving up on the perfect custom font for your design is not an exciting approach, but it’s perfectly viable — especially if you consider this as a transitory stance until cutting edge solutions, which are already on the horizon, gain wide browser support.

为您的设计放弃完美的自定义字体并不是一种令人兴奋的方法,但它是完全可行的-特别是如果您将其视为一种过渡立场,直到即将出现的尖端解决方案获得广泛的浏览器支持。

Opting for this approach doesn’t require you to use @font-face. You just add your font stack to the CSS font-family property. Here’s how you could do this today:

选择这种方法不需要您使用@font-face 。 您只需将字体堆栈添加到CSS font-family属性。 您今天可以执行以下操作:

body {
  font-family: -apple-system,
    BlinkMacSystemFont,
    "Segoe UI",
    Roboto,
    Oxygen-Sans,
    Ubuntu,
    Cantarell,
    "Helvetica Neue",
    sans-serif;
}

The New System Font Stack?’, by Aderinokun, provides more information on the modern font stack.

新系统字体堆栈? 由Aderinokun撰写,提供了有关现代字体堆栈的更多信息。

Web字体加载器 (The Web Font Loader)

One long-standing solution is the Web Font Loader, a JavaScript library developed by Google and Typekit, which works with fonts coming from multiple sources — such as Google Fonts, Typekit, your self-hosted font files, etc.

一个长期的解决方案是Web Font Loader ,这是由Google和Typekit开发JavaScript库,可与来自多种来源的字体(例如Google Fonts,Typekit,您的自托管字体文件等)一起使用。

The Web Font Loader loads custom fonts as a background process while displaying fallback fonts to users, thereby avoiding FOIT. You can set a time limit of your choice within which the font must load. If the request exceeds this limit, users will only see the text styled with a fallback font. Once the custom font is loaded, the script swaps the fallback font on the page with the custom font.

Web字体加载程序将自定义字体作为后台进程加载,同时向用户显示备用字体,从而避免了FOIT。 您可以设置选择的时间限制,必须在该时间限制内加载字体。 如果请求超出此限制,则用户将仅看到使用后备字体设置样式的文本。 加载自定义字体后,脚本会将页面上的后备字体替换为自定义字体。

Here are two awesome tutorials to learn how to use the Web Font Loader:

这是两个很棒的教程,以学习如何使用Web Font Loader:

  • How to Improve Page Performance with a Font Loader

    如何使用字体加载器提高页面性能

  • Loading Web Fonts with the Web Font Loader

    使用Web字体加载器加载Web字体

CSS字体加载API (The CSS Font Loading API)

The CSS Font Loading API is a standards-based way of loading and taking control of web fonts.

CSS字体加载API是一种基于标准的加载和控制Web字体的方法。

The overall recommended approach remains that of avoiding FOIT and managing FOUT as best as possible. This API can keep track of every stage of font loading. You can use this information to style text using web-safe fonts while fonts are not available and style text using custom fonts once these are fully loaded.

总体推荐的方法仍然是避免FOIT和尽可能最佳地管理FOUT。 该API可以跟踪字体加载的每个阶段。 当字体不可用时,您可以使用此信息来使用网络安全字体来设置文本样式,并在完全加载后使用自定义字体来设置文本样式。

At the time of writing, the latest versions of Chrome, Firefox, Safari and Opera support this API, while IE/Edge doesn’t offer support yet. However, you can use a small JavaScript library, the Font Face Observer, to polyfill the native CSS Font Loading API, or simply let non-supporting browsers degrade gracefully to web-safe fonts.

在撰写本文时,最新版本的Chrome,Firefox,Safari和Opera支持此API ,而IE / Edge尚不提供支持。 但是,您可以使用小型JavaScript库Font Face Observer来填充本机CSS Font Loading API,或者只是让不支持的浏览器优雅地降级为网络安全字体。

For a short tutorial on how to use the CSS Font Loading API, head over to Getting started with CSS Font Loading by Manuel Matuzovic and have a look at his CodePen demo.

有关如何使用CSS字体加载API的简短教程,请转至Manuel Matuzovic的CSS字体加载入门,并查看其CodePen演示 。

Since their first appearance, you’ve handled custom fonts using CSS @font-face and font-family. It’s only fair to expect CSS to solve any issue related to downloading custom fonts. But at present, only JavaScript-based solutions are usable.

自首次出现以来,您已经使用CSS @font-facefont-family处理自定义字体。 期望CSS解决与下载自定义字体有关的任何问题,这是公平的。 但是目前,仅基于JavaScript的解决方案可用。

However, this won’t be so indefinitely. A smart CSS property is around the corner, font-display, which is part of the CSS Font Rendering Controls Module Level 1.

但是,这不会是无限期的。 一个灵巧CSS属性font-display ,它是CSS Font Rendering Controls Module Level 1的一部分 。

font-display lets you:

font-display可让您:

  • Decide if you want to show text using a fallback font or hide it while the font is loading.

    确定是要使用后备字体显示文本还是在加载字体时隐藏文本。
  • Control what you want to do once the font has loaded, i.e., continue to show the fallback font or replace it with the custom font. You can also do so on a per-element basis.

    控制字体加载后要执行的操作,即继续显示后备字体或将其替换为自定义字体。 您也可以按元素进行操作。
  • Specify your own timeout values for each font and even for a specific element.

    为每种字体甚至特定元素指定您自己的超时值。

Here’s what this property looks like in code:

这是此属性在代码中的样子:

@font-face {
  font-family: Lato;
  src: url('/web/css/fonts/lato/lato-regular-webfont.woff2') format('woff2'),
  url('/web/css/fonts/lato/lato-regular-webfont.woff') format('woff');
  font-weight: 400;
  font-style: normal;

  /* This value replaces fallback when font has loaded */
  font-display: swap;
}

body {
  font-family: Lato, sans-serif;
  font-weight: 400;
  font-style: normal;
}

Accepted values for this property are:

此属性的接受值为:

  • auto: browsers just implement their default behavior.

    auto :浏览器仅实现其默认行为。

  • block: browsers draw invisible text while the font is loading and replace it with the desired font as soon as it’s loaded.

    block :浏览器在加载字体时绘制不可见的文本,并在加载后立即将其替换为所需的字体。

  • swap: browsers use a fallback font while the custom font isn’t available, but swap the custom font in as soon as it loads.

    swap :浏览器在自定义字体不可用时使用后备字体,但在加载后立即交换自定义字体。

  • fallback: similar behavior to swap. However, if too much time passes until the custom font loads, browsers use the fallback font for the duration of the page’s lifetime.

    后备(fallback) :与swap类似的行为。 但是,如果在加载自定义字体之前花费了太多时间,浏览器将在页面生命周期内使用后备字体。

  • optional: this super smart value lets browsers use the custom font only if it’s already available. If it isn’t, browsers use the fallback for the duration of the page’s lifetime. The custom font may still be downloaded in the background for use on subsequent page loads. However, if browsers detect limited bandwidth on users’ devices, they might not load the custom font at all.

    可选 :此超级智能值允许浏览器仅在自定义字体可用时使用它。 如果不是,浏览器将在页面生命周期内使用后备。 自定义字体可能仍会在后台下载,以用于后续页面加载。 但是,如果浏览器检测到用户设备上的带宽有限,它们可能根本不会加载自定义字体。

From these short descriptions, you can already see how swap and optional could be super useful.

从这些简短的描述中,您已经可以看到swapoptional是多么有用。

Browser support for font-display is non-existent at this time, but it can be enabled in Chrome (via the Experimental Web Platform features” flag) and Firefox (via the layout.css.font-display.enabled flag).

目前没有浏览器对font-display 支持 ,但可以在Chrome(通过“实验性Web平台功能”标志)和Firefox(通过layout.css.font-display.enabled标志)中启用。

Although all the approaches outlined above make possible the elimination of FOIT, either by swapping in the custom font at a later time or by displaying just the fallback font, they can do little against FOUT.

尽管上面概述的所有方法都可以消除FOIT,无论是通过稍后交换自定义字体还是仅显示后备字体,它们对FOUT都无济于事。

Although FOUT makes text still available to users, it can very well be annoying, especially when the fallback font is wider and/or higher than the custom font it is temporarily replacing, which often causes a shift in the page content.

尽管FOUT使文本仍然可供用户使用,但它很令人讨厌,尤其是当后备字体比临时替换的自定义字体更宽和/或更高时,这通常会导致页面内容发生偏移。

You can mitigate the jarring effect of the swap by adjusting the fallback font’s x-height and width so as to match the desired custom font’s x-height and width as closely as possible.

您可以通过调整后备字体的x-height和width来减轻交换的震荡效果,从而尽可能地匹配所需的自定义字体的x-height和width。

You can do this in a number of ways, but I find this little Font Style Matcher tool by Monica Dinculescu really helpful.

您可以通过多种方式来执行此操作,但是我发现Monica Dinculescu的这个小的Font Style Matcher工具确实很有帮助。

In this article I’ve outlined the issues of file size and Flash of Invisible Text related to using custom fonts on websites.

在本文中,我概述了与在网站上使用自定义字体有关的文件大小和不可见文本闪烁的问题。

I’ve presented the latest approaches and pointed you to further resources where you can read more and learn how to implement those techniques in your projects.

我已经介绍了最新的方法,并向您指出了更多的资源,您可以在其中阅读更多信息,并了解如何在项目中实现这些技术。

翻译自: https://www.sitepoint.com/optimizing-web-fonts-for-performance-the-state-of-the-art/

web字体库加载优化

web字体库加载优化_优化Web字体以提高性能:最新技术相关教程

  1. 在WordPress中加载样式和脚本的条件标签
  2. Haproxy搭建Web群集理论和实验篇
  3. 【Web】Bootstrap框架学习笔记之 其他资源整理
  4. node.js web框架_TestCafe:使用Node.js更轻松地进行端到端Web应
  5. JavaWeb一些配置介绍
  6. 【Springboot】 with a RESTful Web Service
  7. WebApi 接口增加备注和测试
  8. 电商系统前后端开发(Vue+SSM)(8) - 新建 webpack simple 项目