Skip to main content

Webfonts

Optimizing web font delivery plays a crucial role in enhancing website performance. Swift font detection by browsers allows for a smoother and quicker text rendering experience, which can lead to improved perceived performance. Here's how you can manage font-face declarations in your Craft CMS projects for better performance:

Storing Fonts

First, make sure to store your font files in the right location. All .woff2 or .woff font files should be placed within the /web/fonts directory. This ensures that they are easily accessible to the browser while also keeping your file structure organized.

Font-Face CSS Declaration

For declaring your fonts, use the following approach within the templates/_abstracts/font-face.twig file:

<style>
   @font-face {
      font-display: swap;
      font-family: 'inter';
      src: url('/fonts/inter-regular.woff2') format('woff2');
      font-weight: normal;
      font-style: normal;
   }

   @font-face {
      font-display: swap;
      font-family: 'inter';
      src: url('/fonts/inter-regular-italic.woff2') format('woff2');
      font-weight: normal;
      font-style: italic;
   }
</style>
Here, we are using the font-display: swap; property, which is highly recommended for performance as it instructs the browser to use fallback fonts until the custom font has fully downloaded.

Integration in Layout

This _abstracts/font-face.twig file should be included in the <head> of your main layout file. In Overdog, the following line of code accomplishes this. This directive ensures that the font-face styles are prioritized in the loading sequence.

{{ include('_abstracts/font-face.twig', ignore_missing = true) }}

Utilizing Font Services

In case you are using a font service like Google Fonts or Adobe Fonts, the process is straightforward. You can simply add the external stylesheet link provided by the service to your layout file, as you would normally do in any other project.

For instance:

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

If you choose to use an external font service, you can opt to remove the include line for the font-face file, as it becomes unnecessary.