font-loader.tsx 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. "use client";
  2. import { useEffect } from "react";
  3. import { onIdle } from "@/lib/utils";
  4. /**
  5. * Brings in the display face after the first paint, so it never holds up the
  6. * first frame. Until then headings use a fallback with matching metrics, so
  7. * nothing shifts when it swaps in. Returning visitors already have the font
  8. * cached; an inline script in <head> switches it on before their first paint.
  9. */
  10. export function FontLoader({ faces }: { faces: string[] }) {
  11. useEffect(() => {
  12. const root = document.documentElement;
  13. if (root.classList.contains("ff")) return;
  14. let live = true;
  15. const cancel = onIdle(() => {
  16. Promise.all(faces.map((face) => document.fonts.load(face)))
  17. .then(() => {
  18. if (!live) return;
  19. root.classList.add("ff", "ff-in");
  20. try {
  21. localStorage.setItem("ff", "1");
  22. } catch {}
  23. })
  24. .catch(() => {});
  25. }, 800);
  26. return () => {
  27. live = false;
  28. cancel();
  29. };
  30. }, [faces]);
  31. return null;
  32. }