Gatsby.js:在没有渲染阻止的情况下为版式主题加载Google字体

dou*_*lin 8 typography google-font-api google-pagespeed gatsby render-blocking

我正在使用Gatsby.js及其带有Irving主题的Typography插件.

此主题需要Google字体"Exo""Yrsa",并<head>在导出的静态html文件部分添加导入:

<link href="//fonts.googleapis.com/css?family=Exo:700|Yrsa:400,700" rel="stylesheet" type="text/css"/>
Run Code Online (Sandbox Code Playgroud)

此导入是渲染阻止内容,如果可能,我会更愿意避免使用这些内容和Google PageSpeed Insights分数.

我尝试使用gatsby-plugin-google-fonts并将以下内容添加到我的gatsby-config.js中:

{
  resolve: `gatsby-plugin-google-fonts`,
  options: {
    fonts: [
      `Exo\:700`,
      `Yrsa\:400,700`,
    ],
  }
},
Run Code Online (Sandbox Code Playgroud)

然而,这只是添加了第二个导入调用.我应该将它们放在静态目录中吗?即使这样,我如何配置Typography仍然使用这些字体而不单独导入它们?

Rom*_*cea 4

您可能会获得更好的结果font-display:swap。不幸的是,Google 托管的字体尚不支持此功能,因此,我使用typeface-* npm 包自行托管我的字体,该包是由 Kyle 创建的,他也做 Gatsby。

这也有助于您的应用程序在没有互联网连接的情况下更好地工作,因为您使用的是 Gatsby 并且您可能会添加离线插件。有些国家甚至可能禁用谷歌。

如果您还使用排版插件,这里是从Qards中提取的示例配置代码:

import Typography from "typography";

let bodyFontFamily = ["Roboto", "Helvetica", "Arial", "sans-serif"];
let headerFontFamily = bodyFontFamily;

const typography = new Typography({
    baseFontSize    : "16px",
    baseLineHeight  : 1,
    omitGoogleFont  : true,
    headerFontFamily: headerFontFamily,
    bodyFontFamily  : bodyFontFamily
});

export default typography;
Run Code Online (Sandbox Code Playgroud)

gatsby-browser.js:

exports.onInitialClientRender = () => {
  require("typeface-roboto");
};
Run Code Online (Sandbox Code Playgroud)