Skip to content
Johan Janssens edited this page Apr 8, 2021 · 1 revision

Font Loading

While it's still possible to load fonts remotely directly from Google, there are several benefits in loading fonts locally into the project.

Primarily, it saves you an additional DNS request, and prevents Google from additional tracking.

It also gives you the option of making font-loading a 'not-required', allowing users on slow connections to fall back to system defaults when necessary.

Steps to include fonts locally

  1. Use https://google-webfonts-helper.herokuapp.com/fonts to find the required fonts
  2. Select only the glyphs required (more fonts = larger download for the user)
  3. Decide whether you need to support older browsers, or just modern browsers (reducing the amount of font-faces that are going to be loaded)
  4. Load the fonts asynchronously using the technique in the Go Make Things link below
  5. Make sure you have 'font-display: swap' defined in css file - this will allow the font to be swapped after loading.
  6. Include the font-face css via a lazy-loading technique:

<link rel="stylesheet" href="theme://css/fonts.css" media="print" onload="this.media='all'; this.onload=null;" />

The end result is:

  • The font is lazy loaded
  • The browser will use the default font defined in css initially
  • The browser will then swap to the preferred font when it's loaded

The upside is that text will be visible immediately, the downside is you may see the font-face swap when it loads.

More info:

Tailwind

Using custom fonts in Tailwind with Mason

If you'd like to replace the default 'font-sans' and 'font-serif' with fonts of your own choice, there's two things you need to add to your Mason config.

After the first line of the default Mason config that defines the mason constant, add this line:

const defaultTheme = require("tailwindcss/defaultTheme");

This gives you access to the default Tailwind theme variables.

In the Tailwind section of your Mason config file you need to add to the 'extend' section:

extend: {
  fontFamily: {
    sans: ["Roboto", ...defaultTheme.fontFamily.sans],
    serif: ["Roboto\ Slab", ...defaultTheme.fontFamily.sans]
  }
}

This will then use the fonts you've selected as the defaults for the theme.

More info & other methods: https://www.tailwindtoolbox.com/guides/adding-fonts-to-tailwind-css