盖茨比.js:为排版主题加载谷歌字体,而无需渲染阻止



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

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

<link href="//fonts.googleapis.com/css?family=Exo:700|Yrsa:400,700" rel="stylesheet" type="text/css"/>

此导入是渲染阻塞内容,如果可能的话,我宁愿避免它对于用户和我的 Google PageSpeed Insights 分数。

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

{
  resolve: `gatsby-plugin-google-fonts`,
  options: {
    fonts: [
      `Exo:700`,
      `Yrsa:400,700`,
    ],
  }
},

但是,这只会添加第二个导入调用。我应该将它们放在静态目录中吗?即便如此,我如何配置排版以仍然使用这些字体而不单独导入它们?

使用 font-display:swap 可能会获得更好的结果。不幸的是,谷歌托管的字体还不支持此功能,所以,相反,我使用 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;

Gatsby-browser.js:

exports.onInitialClientRender = () => {
  require("typeface-roboto");
};

最新更新