PageSpeed Insights 诊断 "Ensure text remains visible during webfont load"

PageSpeed Insights diagnostic "Ensure text remains visible during webfont load"

我正在 PageSpeed Insights

上进行诊断
Ensure text remains visible during webfont load
Leverage the font-display CSS feature to ensure text is user-visible while webfonts are loading. Learn more.
URL
    
Potential Savings
…v1/aWB4m0aac….woff2(fonts.gstatic.com)     10 ms
…v21/nuFvD-vYS….woff2(fonts.gstatic.com)    10 ms
…v13/6xK3dSBYK….woff2(fonts.gstatic.com)    10 ms

我正在尝试通过更改

来纠正它
  <link rel="stylesheet" href="https://fonts.googleapis.com" />

<link rel="stylesheet" href="https://fonts.googleapis.com/display=swap" />

但这实际上会引发控制台错误


我知道PageSpeed Insights recommends to addfont-display: swap@fontface,但我不知道@fontface是什么

我正在使用 BootstrapGatsby

我知道还有 gatsby-plugin-web-font-loader。有没有办法使用它来避免这种诊断?


这些都是 font-family 在我的程序中出现的次数。我用的是 scss 所以大部分都是变量

我在我的程序中只指定了一次字体,我认为 bootstrap 在其余时间选择字体

blockquote > p {
   font-family: 'Montserrat', sans-serif;
}

更新,我现在正在使用这个插件

{
  resolve: `gatsby-plugin-google-fonts`,
  options: {
    fonts: [
      `Montserrat`,
      `Helvetica Neue`,
      `Helvetica`,
      `Arial`
      
    ],
    display: 'swap'
  }
},

你犯了一个小错误。

应该是

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=TheFontYouWantToUse&display=swap />

如果您按照示例中所示使用正斜杠,将导致 404 未找到,因此会出现控制台错误。将其替换为 URL 参数 (&),它应该可以正常工作。

@fontface 只是一种从样式表中加载字体的方法。

例如,在您的主 CSS 文件中,您可以添加以下内容,这也会加载字体。请注意 font-display 属性 设置为 swap

@font-face {
  font-family: 'Pacifico';
  font-style: normal;
  font-weight: 400;
  src: local('Pacifico Regular'), local('Pacifico-Regular'), url(https://fonts.gstatic.com/s/pacifico/v12/FwZY7-Qmy14u9lezJ-6H6MmBp0u-.woff2) format('woff2');
  font-display: swap;
}

@font-face 是允许您使用多个 font-family 规则而不是在每个选择器中加载它的规则。

在 Gatsby 的所有字体插件中,我推荐 gatsby-plugin-google-fonts 因为它允许您显示和切换字体。

 plugins: [
    {
      resolve: `gatsby-plugin-google-fonts`,
      options: {
        fonts: [
          `limelight`,
          `source sans pro\:300,400,400i,700` // you can also specify font weights and styles
        ],
        display: 'swap'
      }
    }
  ]

它非常有用,因为它预加载字体而不影响显示(由于 swap 属性)。

使用 Gatsby,<link rel="stylesheet" href="https://fonts.googleapis.com" /> 此配置是自动进行的,因此您无需触摸它。最好使用插件预渲染它们,因为它是 Gatsby 的强大功能。