Home  >  Article  >  Web Front-end  >  How to Efficiently Load Google Fonts in Nuxt.js?

How to Efficiently Load Google Fonts in Nuxt.js?

DDD
DDDOriginal
2024-11-02 03:53:02661browse

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.

The above is the detailed content of How to Efficiently Load Google Fonts in Nuxt.js?. 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