Optimizing Fonts and Images (Next.js)

Rmag Breaking News

Using custom fonts in your project can affect performance if the font files need to be fetched and loaded.

Cumulative Layout Shift is a metric to evaluate the performance and user experience of a website. Layout shift happens can cause the text size, spacing, or layout to change, shifting elements around it.

Next.js automatically optimizes fonts in the application when you use the next/font module. It downloads font files at build time and hosts them with your other static assets. This means when a user visits your application, there are no additional network requests for fonts.

View my commits on GitHub:

Add fonts

Add images

Adding a primary font

Use /app/ui/fonts.ts to keep the fonts that will be used throughout your application.

By adding Inter to the <body> element, the font will be applied throughout. The Tailwind antialiased class smooths out the font.

Adding a secondary font

If you’re unsure what weight options to pass to a font, check the TypeScript errors in your code editor.

Visit Google Fonts and search for Lusitana to see what options are available.

See the documentation for adding multiple fonts and the full list of options.

Optimize Images

Next.js can serve static assets, like images, under the top-level /public folder. Files inside /public can be referenced in your application.

With regular HTML, you manually:

Ensure your image is responsive on different screen sizes.
Specify image sizes for different devices.
Prevent layout shift as the images load.
Lazy load images that are outside the user’s viewport.

The next/image component automatically optimizes your images. The <Image> Component is an extension of the HTML <img> tag, and comes with automatic image optimization, such as:

Preventing layout shift automatically when images are loading.
Resizing images to avoid shipping large images to devices with a smaller viewport.
Lazy loading images by default (images load as they enter the viewport).
Serving images in modern formats, like WebP and AVIF, when the browser supports it.

It’s good practice to set the width and height of your images to avoid layout shift, these should be an aspect ratio identical to the source image.

Dive deeper into fonts and images:

https://nextjs.org/docs/app/building-your-application/optimizing/images

https://nextjs.org/docs/app/building-your-application/optimizing/fonts

https://developer.mozilla.org/en-US/docs/Learn/Performance/Multimedia

https://developer.mozilla.org/en-US/docs/Learn/CSS/Styling_text/Web_fonts

Leave a Reply

Your email address will not be published. Required fields are marked *