FOIT font loading

  • Post author:
  • Post category:PMF
  • Post comments:0 Comments

To prevent text on your website showing the default fonts which the font-face is loading, this is how you do it.

We basically hide the <body> of the page until the fonts are loaded.

/* Javascript to load font faces so that we get FOIT on the page and
we don't see the font switch from the default to the loaded font */
<script>
document.querySelector("body").style.visibility = "hidden";
const font = new FontFace("Lato", "url(/fonts/Lato-Regular.ttf)");
font.load().then (() => {
  document.fonts.add(font);
  document.body.style.fontFamily = "Lato, serif";
  document.querySelector("body").style.visibility = "visible";
});
</script>

Now you can refer to your font-family in your css as below:

  body {
    font-family: Lato;
  }

  html {
    font-size: 1em;
    font-family: Lato;
    color: #333;
    line-height: 1.5rem;
  }

Leave a Reply