Ottimizzazione di immagini e font
Utilizzi i componenti Image e Font integrati in Next.js per ottenere un'ottimizzazione automatica e migliori prestazioni di caricamento.
Ottimizzazione di immagini e font è una lezione Next.js 15 Fullstack (App Router + Server Actions) gratuita su CoddyKit. Questa è la lezione 1 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Next.js 15 Fullstack (App Router + Server Actions), e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Next.js 15 Fullstack (App Router + Server Actions) include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Why Optimize Assets?
Web performance is crucial for user experience and SEO. Large images and unoptimized fonts can significantly slow down your website.
Next.js provides built-in components to automatically optimize these assets, making your applications faster and more efficient.
Image Loading Challenges
Traditionally, developers face challenges with images:
- Large File Sizes: Slow downloads, high bandwidth usage.
- Incorrect Dimensions: Serving huge images to small screens.
- Layout Shifts (CLS): Images loading late, pushing content around.
- Accessibility: Missing
altattributes.
Meet `next/image`
Next.js's Image component (from next/image) is a powerful tool designed to solve these problems automatically. It handles:
- Automatic Optimization: Converts images to modern formats like WebP.
- Responsive Sizing: Serves different image sizes based on device.
- Lazy Loading: Loads images only when they enter the viewport.
- Preventing CLS: Ensures images occupy space before loading.
Basic `next/image` Usage
To use Image, simply import it and replace your standard <img> tags. You must provide width, height, and alt props.
Try running this example (assuming /my-image.jpg is in your public folder):
import Image from 'next/image';
export default function HomePage() {
return (
<div>
<h1>Optimized Image</h1>
<Image
src="/my-image.jpg"
alt="A beautiful landscape"
width={500}
height={300}
/>
<p>This image is now optimized!</p>
</div>
);
}Key Image Props
Let's look at essential props for the Image component:
src: Path to your image (local or external).alt: Crucial for accessibility and SEO.width,height: Specify intrinsic dimensions to prevent layout shifts.priority: (Optional) Load image immediately if it's above the fold.
Image Layout with `fill`
For images that should fill their parent container, use the fill prop. This is great for hero images or backgrounds.
The parent element needs position: 'relative' to act as the container for the filled image.
import Image from 'next/image';
export default function Banner() {
return (
<div style={{
position: 'relative',
width: '100%',
height: '200px',
backgroundColor: '#eee'
}}>
<Image
src="/banner.jpg"
alt="Website banner"
fill
style={{ objectFit: 'cover' }}
sizes="(max-width: 768px) 100vw, 50vw"
/>
<h2 style={{ position: 'absolute', color: 'white', zIndex: 10 }}>
Awesome Banner
</h2>
</div>
);
}The Need for Font Optimization
Custom fonts add personality to your site, but they can be large files, leading to performance issues like:
- FOIT (Flash of Invisible Text): Text is invisible until the font loads.
- FOUT (Flash of Unstyled Text): Text displays in a default font, then switches.
- Large Bundles: Font files increase overall page weight.
Next.js's next/font module helps tackle these challenges.
Optimizing Google Fonts
next/font/google automatically optimizes Google Fonts, downloading them at build time and self-hosting them with strong caching. This eliminates external network requests and ensures consistent loading.
Apply the font's class name to your HTML or a specific element:
import { Inter } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
display: 'swap', // Prevents FOIT
});
export default function AppLayout({ children }) {
return (
<html lang="en" className={inter.className}>
<body>
<h1>My App Header</h1>
{children}
</body>
</html>
);
}Using Local Fonts
For self-hosted fonts (fonts you provide), use next/font/local. It works similarly to next/font/google, optimizing the font loading process for your local files.
Place your font files (e.g., .woff2) in the public directory or a dedicated fonts folder.
import localFont from 'next/font/local';
const myCustomFont = localFont({
src: './fonts/MyCustomFont.woff2',
display: 'swap',
});
export default function AboutPage() {
return (
<div className={myCustomFont.className}>
<h2>About Us</h2>
<p>This page uses a custom font.</p>
</div>
);
}Optimize Your Assets
Which of the following are benefits of using Next.js's Image and Font components for asset optimization?
Recap: Optimized Assets
You've learned how Next.js empowers you to optimize critical assets like images and fonts:
- The
next/imagecomponent offers automatic optimization, lazy loading, and CLS prevention. - The
next/fontmodule ensures efficient loading of both Google and local fonts, improving performance and visual stability.
By using these components, you significantly enhance your application's speed and user experience!
Impara TypeScript con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 22
- Lezioni
- 88
Domande Frequenti
La lezione «Ottimizzazione di immagini e font» è gratuita?
Sì — il testo completo di «Ottimizzazione di immagini e font» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Next.js 15 Fullstack (App Router + Server Actions), passa a CoddyKit PRO. Il corso Next.js 15 Fullstack (App Router + Server Actions) include 4 lezioni in totale.
Cosa imparerò in «Ottimizzazione di immagini e font»?
Utilizzi i componenti Image e Font integrati in Next.js per ottenere un'ottimizzazione automatica e migliori prestazioni di caricamento. Eserciti Next.js 15 Fullstack (App Router + Server Actions) con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Next.js 15 Fullstack (App Router + Server Actions)?
Non è richiesta alcuna esperienza precedente. Next.js 15 Fullstack (App Router + Server Actions) su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 1 di 4.
Quanto tempo richiede la lezione «Ottimizzazione di immagini e font»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Next.js 15 Fullstack (App Router + Server Actions)?
Sì. Ogni lezione Next.js 15 Fullstack (App Router + Server Actions) include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Ottimizzazione di immagini e font
- Analisi delle dimensioni del bundle
- Strategie avanzate di caching
- UI in streaming con Suspense e stati di caricamento