Use font-display for Google Fonts


How to use 'font-display' descriptor for a website that uses Google Fonts.





TLDR : If you are looking for a single line hack to achieve this - there isn't any (as of Nov 2018). The only way to use 'font-display' for Google fonts is to self-host them. This how-to provides easiest way to reliably self-host Google fonts and add 'font-display' descriptor to self-hosted fonts.


Introduction

Using 'font-display' with an appropriate value ensures that the text is displayed even before webfont files are downloaded. For this, the 'font-display' descriptor needs to be added to @font-face rule for the specific webfont. When using Google fonts, the CSS containing @font-face rule(s) is hosted by Google (like this) and you cannot alter the content of this file. Also, you should not just copy the contents of Google's fonts css to a self-hosted CSS since Google generates different CSS files for different browsers.


So, the recommended approach to go about this is:


Generate a Cross-Browser Compatible Fonts CSS

Use Google Webfonts Helper to generate a cross-browser compatible CSS file as detailed below:


Add 'font-display' Descriptor

You can now add 'font-display' to @font-face rules of the copied CSS. While you may chose the right font-display value based on your requirements, we have found that the value 'swap' fits most requrements.


/* lato-100 - latin */
@font-face {
  font-family: 'Lato';
  font-style: normal;
  font-weight: 100;
  src: url('../fonts/lato-v14-latin-100.eot'); /* IE9 Compat Modes */
  src: local('Lato Hairline'), local('Lato-Hairline'),
       url('../fonts/lato-v14-latin-100.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('../fonts/lato-v14-latin-100.woff2') format('woff2'), /* Super Modern Browsers */
       url('../fonts/lato-v14-latin-100.woff') format('woff'), /* Modern Browsers */
       url('../fonts/lato-v14-latin-100.ttf') format('truetype'), /* Safari, Android, iOS */
       url('../fonts/lato-v14-latin-100.svg#Lato') format('svg'); /* Legacy iOS */
  font-display: 'swap';
}

Self-host Generated CSS and Fonts

You may want to modify the './fonts/' path within the generated CSS to a location where font files are actually hosted. Other than that, you just need to host the generated CSS (either as a separate CSS file or as part of existing CSS file) and font files onto your server.






Looking to improve your website's speed? Let Tezify team take care of your website's performance intricacies.