"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Efficiently Load Google Fonts in Nuxt.js?

How to Efficiently Load Google Fonts in Nuxt.js?

Published on 2024-11-07
Browse:365

How to Efficiently Load Google Fonts in Nuxt.js?

Best Way to Efficiently Load Google Fonts in Nuxt

When working with multiple components that require different font weights from the same Google font, it's important to avoid the redundant practice of importing multiple links in Layout.vue.

To address this issue and optimize font loading in NuxtJS projects, it's recommended to utilize the @nuxtjs/google-fonts module. This module offers an efficient and centralized approach to manage Google font imports.

Using @nuxtjs/google-fonts Module

  1. Install the module:
npm install @nuxtjs/google-fonts
  1. Add the module to your nuxt.config.js file:
export default {
  buildModules: [
    [
      '@nuxtjs/google-fonts',
      {
        families: {
          'Saira Semi Condensed': {
            wght: [600, 800],
          },
        },
        display: 'swap', // Load fonts as soon as possible
        prefetch: false, // Don't prefetch fonts
        preconnect: false, // Don't preconnect to font server
        preload: false, // Don't preload fonts
        download: true, // Download fonts for offline use
        base64: false, // Don't base64 encode fonts
      },
    ],
  ],
}
  1. Import the fonts in your component style using the @font-face rule:
@font-face {
  font-family: 'Saira Semi Condensed', sans-serif;
  font-weight: 600;
  font-style: normal;
  src: local('Saira Semi Condensed'), local('SairaSemiCondensed-Wght600'),
  url("https://fonts.gstatic.com/s/sairasemicondensed/v15/E6qS90ZBdhyxr0K917oteYGc.woff2") format('woff2');
}

Additional Notes:

  • If specific font weights are not being downloaded, set overwriting: true in the module configuration or update the package to v3.0.0-1.
  • Self-hosting Google Fonts is generally preferable to using a CDN for performance optimization. Consider using google-webfonts-helper for self-hosting.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3