A user reported the following issue with our multi-tenancy web page editor app. They noticed that their app is loading all 100 available fonts by default, even when only a few are actually used on each page. This is causing their bundle size to be much larger than necessary, which is impacting the app's performance.
As a user, they can select from any of these 100 fonts, and each page they create might use multiple different fonts. However, they concerned that loading all these fonts upfront is overkill and slowing down the initial page load.
Is there a way to optimize this? Ideally, they only load the fonts that are actually being used on each specific page. I know Next.js has some font optimization features, and it would be great if they could leverage those to prevent unnecessary font downloads.
Let's implement a solution to optimize font loading in your multi-tenancy web page editor app using Next.js font optimization features. We'll create a system that dynamically loads only the fonts used on each specific page.
This implementation provides a solution to the user's issue by:
next/font in a central location.usePageFonts) that allows components to specify which fonts they need.Here's how it works:
FontProvider component manages the state of loaded fonts.usePageFonts hook is used in each page component to specify which fonts are needed for that page.next/font module handles the actual font loading and optimization.This approach significantly reduces the initial bundle size by preventing unnecessary font downloads. Only the fonts that are actually used on each page will be loaded, improving the app's performance 12.
To implement this in the existing multi-tenancy web page editor app:
usePageFonts hook, specifying the fonts it needs.FontProvider is wrapped around the main application component.This solution leverages Next.js's font optimization features while providing a flexible system for dynamically loading fonts as needed across different pages in the application 3.
Sources