Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gatsby.js: Load Google Fonts for Typography themes without Render-Blocking

I'm using Gatsby.js and its Typography plugin with the Irving theme.

This theme requires the Google Fonts "Exo" and "Yrsa", and adds an import to the <head> section of the exported static html files:

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

This import is render-blocking content and I'd prefer to avoid it if possible for both users and my Google PageSpeed Insights score.

I tried using gatsby-plugin-google-fonts and added the following to my gatsby-config.js:

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

However this just adds a second import call. Should I be placing them in the static directory? Even then, how can I configure Typography to still use these fonts without importing them separately?

like image 715
dougmacklin Avatar asked Jan 22 '18 18:01

dougmacklin


1 Answers

You might get better results with font-display:swap. Unfortunately Google hosted fonts do not support this feature yet so, instead, I went for self-hosting my fonts using the typeface-* npm package which are created by Kyle who also does Gatsby.

This also helps your app work better without internet connection since you're using Gatsby and you might add the offline plugin. Some countries might even have google disabled.

If you're also using the typography plugin here's the sample config code extracted from 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");
};
like image 84
Romeo Mihalcea Avatar answered Nov 16 '22 03:11

Romeo Mihalcea