Home > database >  Is it okay to put fonts and it's related css in the public directory, and preloading them using
Is it okay to put fonts and it's related css in the public directory, and preloading them using

Time:10-20

I'm trying to optimize the use of fonts in my Nuxt 3 application. Nuxt 3 documentations suggest to put the fonts in the assets directory, but I wanted to preload the fonts for better performance, so I've added them and the css file that defines my font-faces to the public directory, and added them to my project via app.vue file like this

app.vue

<template>
  <Head>
    <link rel="preload" as="style" href="/fonts/font.css" crossorigin="anonymous">
  </Head>
  <nuxt-layout>
    <nuxt-page />
  </nuxt-layout>
</template>

Here is my font.css file which is placed in the ~/public/fonts directory, next to my font files:

@font-face {
  font-family: "Urbanist";
  src: url("/fonts/Urbanist/Urbanist[wght].woff2") format('woff2'),
    url("/fonts/Urbanist/Urbanist[wght].ttf") format('truetype');
  font-weight: 100 900;
  font-display: swap;
}

@font-face {
  font-family: "Lato";
  src: url("/fonts/Lato/Lato-Light.woff2") format('woff2'),
    url("/fonts/Lato/Lato-Light.ttf") format('truetype');
  font-weight: 300;
  font-display: swap;
}
@font-face {
  font-family: "Lato";
  src: url("/fonts/Lato/Lato-Regular.woff2") format('woff2'),
    url("/fonts/Lato/Lato-Regular.ttf") format('truetype');
  font-weight: 400;
  font-display: swap;
}
@font-face {
  font-family: "Lato";
  src: url("/fonts/Lato/Lato-Bold.woff2") format('woff2'),
    url("/fonts/Lato/Lato-Bold.ttf") format('truetype');
  font-weight: 700;
  font-display: swap;
}
@font-face {
  font-family: "Lato";
  src: url("/fonts/Lato/Lato-Black.woff2") format('woff2'),
    url("/fonts/Lato/Lato-Black.ttf") format('truetype');
  font-weight: 900;
  font-display: swap;
}

Everything is working fine, but I wanted to know if it's the right approach?
Is there a better way to preload my fonts for better performance?

CodePudding user response:

First off, you don't really get anything else from loading it from the public directory or the assets one regarding preloading. You may have some optimizations in the assets one but anyway, preloading a local font is probably not useful and can even make your performance page speed worse (because of your page's loading order).
Give a read to that one: https://web.dev/font-best-practices/#be-cautious-when-using-preload-to-load-fonts

Here is a thread on how to optimize fonts even further: https://twitter.com/filrakowski/status/1582691561741070336
There you will see tools from Meownica and Daniel that could be useful.
Font optimization is a broad topic and I'll recommend following the good practices recommended by experts, on top of using those tools.

Want to go even further? Here you go.


TLDR: follow the recommendations.

  • Related