Home  >  Article  >  Web Front-end  >  How to Efficiently Load Google Fonts in Nuxt with Different Font Weights?

How to Efficiently Load Google Fonts in Nuxt with Different Font Weights?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 12:56:02717browse

How to Efficiently Load Google Fonts in Nuxt with Different Font Weights?

Efficiently Loading Google Fonts in Nuxt

Problem:

In a NuxtJS project, the user wants to use the Saira Semi Condensed font with different font weights (600 and 800) for two different components. However, importing two Google Font links for the same font with different weights leads to redundancy and potential issues with font-weight application.

Solution:

The recommended approach is to self-host or proxy Google Font files through the page origin rather than using a CDN. Nuxt provides the @nuxtjs/google-fonts module that enables efficient and customizable loading of Google Fonts. Here's how to use it:

nuxt.config.js:

export default {
  buildModules: [
    [
      '@nuxtjs/google-fonts',
      {
        families: {
          'Saira Semi Condensed': {
            wght: [600, 800],
          },
        },
        // Other options here...
      },
    ],
  ],
}

Layout.vue (Head section):

<link rel="preload" href="/fonts/SairaSemiCondensed-wght@600.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="/fonts/SairaSemiCondensed-wght@800.woff2" as="font" type="font/woff2" crossorigin="anonymous">

Note: Replace /fonts with the correct path to the downloaded font files.

ComponentA.vue or ComponentB.vue (Style section):

footer {
  font-family: 'Saira Semi Condensed', sans-serif;
  font-weight: 600; /* or 800 for ComponentB */
}

This approach ensures that the specific font weights are downloaded and applied to the respective components, eliminating the need for multiple CDN links.

The above is the detailed content of How to Efficiently Load Google Fonts in Nuxt with Different Font Weights?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn