nuxt-modules / google-fonts

Google Fonts module for NuxtJS
https://google-fonts.nuxtjs.org
MIT License
517 stars 41 forks source link

`preload` for downloaded fonts #182

Open codeflorist opened 7 months ago

codeflorist commented 7 months ago

SEO- and performance-wise it makes sense to add a <link rel="preload" tag for the fonts used by the site. The option preload: true however only works, if download: false is set. It would be great, if it also works with downloaded fonts.

riddla commented 4 months ago

I'm currently using a quick and dirty local Nuxt module for this:

import { defineNuxtModule } from "nuxt/kit";
import { globby } from "globby";
import { basename, extname } from "node:path";

export default defineNuxtModule({
  hooks: {
    ready: async (nuxt) => {
      if (!nuxt.options.nitro.publicAssets) {
        return;
      }

      const googleFontsModuleDir = nuxt.options.nitro.publicAssets.find(
        (assetDirectory) => assetDirectory?.dir?.includes("nuxt-google-fonts")
      );

      if (!googleFontsModuleDir) {
        return;
      }

      const outputDir = googleFontsModuleDir.dir;
      const outputFonts = await globby(outputDir!);

      outputFonts.forEach((fontFilePath) => {
        nuxt.options.app.head.link!.push({
          rel: "preload",
          as: "font",
          type: `font/woff2`,
          href: `/fonts/${basename(fontFilePath)}`,
        });
      });
    },
  },
});
codeflorist commented 4 months ago

@riddla

Nice, thanks!

It's also worth mentioning, that https://github.com/nuxt/fonts has the preload-feature on-board, and it seems, that nuxt/fonts will be the successor package of nuxt-modules/google-fonts (see https://github.com/nuxt/fonts/issues/57)