Loading fonts per page

I’m building a site for a type designer and I want to be able to load each font only when the user navigates to that page. This is the code for the head, but I can’t seem to load the font or use it:

head() {
 return {
  link: [
     {
       rel: "stylesheet",
       href: this.slice.primary.font.url
     }
   ]
 };
}

Two things to check:

  • Does it work correctly when you create a global head link to the font?
  • Is the font request happening? Can you see it being loaded in developer tools?

Hey, I can see the font request in the Network tab, but so for I’ve only gotten it to work when I create a fonts.css file and include it in the nuxt.config.js with the following code

@font-face {
  font-family: "Zephyr";
  src: url("https://prismic-io.s3.amazonaws.com/nuxtprismic/acc28138-2b0c-41d8-9b67-646c28e180b3_Zephyr-Italic.woff2") format("woff2");
  font-weight: 500;
  font-style: normal;
  font-stretch: normal;
}

What about including that CSS in the component’s css?

<template>
  <!-- things here -->
</template>

<script>
export default {
  // more things here
}
</script>

<style scoped>
@font-face {
  font-family: "Zephyr";
  src: url("https://prismic-io.s3.amazonaws.com/nuxtprismic/acc28138-2b0c-41d8-9b67-646c28e180b3_Zephyr-Italic.woff2") format("woff2");
  font-weight: 500;
  font-style: normal;
  font-stretch: normal;
}
</style>

I was finally able to figure it out, by placing that code inside the heads style attribute, so I can access the data from Prismic and making it dynamic:

head() {
 return {
  style: [
    {
      cssText: `@font-face {
      font-family: "${this.slice.primary.font_name}";
      src: url("${this.slice.primary.font.url}") format("woff2");
      font-weight: 500;
      font-style: normal;
      font-stretch: normal;
      }  `,
      type: "text/css"
    }
  ]
};

Thanks for your help!

1 Like