图像与字体优化
使用 `next/image` 优化图像,并高效管理字体以缩短加载时间。
图像与字体优化 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack Web Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Optimize Images & Fonts?
Optimizing images and fonts is crucial for a fast-loading website. Large files slow down your page, impacting user experience and SEO.
- Faster Loading: Users don't wait for slow pages.
- Improved SEO: Search engines favor faster sites.
- Better UX: Smooth, responsive feel.
- Lower Bandwidth: Saves data for users.
Next.js Image Component
Next.js provides a powerful next/image component. It automatically optimizes images for you, handling responsiveness, lazy loading, and format conversion to modern formats like WebP.
Using next/image ensures your images are served in the most efficient way possible, often without you needing to do manual optimization.
Using the Image Component
To use next/image, import it and then define your image's src, alt text, width, and height. The width and height are crucial for preventing layout shifts (CLS).
import Image from 'next/image';
export default function MyImage() {
return (
<Image
src="/my-photo.jpg"
alt="A descriptive alt text"
width={500}
height={300}
/>
);
}Layout Modes & Responsiveness
next/image offers different layout modes to control how images scale:
intrinsic(default): Scales down for smaller viewports, but doesn't scale up beyond its original size.fixed: Image is fixed width and height.fill: Image fills its parent element, useful for background images or when the image dimensions are unknown. Requires the parent to haveposition: relative.
Loading Priority with `priority`
For images above the fold (visible when the page first loads), you should add the priority prop. This tells Next.js to preload the image, improving your site's Largest Contentful Paint (LCP) metric.
Only use priority for critical images, like hero banners. Overusing it can negate its benefits.
import Image from 'next/image';
export default function HeroSection() {
return (
<Image
src="/hero-banner.jpg"
alt="Hero banner for the website"
width={1200}
height={600}
priority
/>
);
}The Need for Font Optimization
Custom fonts can significantly impact performance. Large font files mean longer download times, leading to 'flash of unstyled text' (FOUT) or 'flash of invisible text' (FOIT).
Optimizing fonts reduces file size and ensures they load smoothly, improving the visual experience and preventing layout shifts.
Google Fonts with `next/font`
Next.js 15 simplifies using Google Fonts with next/font/google. It automatically self-hosts fonts, reduces layout shifts (CLS), and improves privacy by avoiding direct requests to Google.
Import your desired font, then apply it to your HTML elements.
import { Inter } from 'next/font/google';
// Configure the Inter font
const inter = Inter({ subsets: ['latin'] });
export default function MyApp({ Component, pageProps }) {
return (
<main className={inter.className}>
<Component {...pageProps} />
</main>
);
}Self-Hosting Local Fonts
For self-hosted fonts (fonts you provide yourself), use next/font/local. This allows you to bundle your font files directly with your application, giving you full control over their delivery.
Define your font source and apply it just like Google Fonts.
import localFont from 'next/font/local';
// Configure a local custom font
const myCustomFont = localFont({ src: './my-custom-font.woff2' });
export default function MyPage() {
return (
<h1 className={myCustomFont.className}>
My Custom Title
</h1>
);
}Font Loading Strategies
To further optimize font loading:
display: swap: This CSS property shows fallback text immediately while the custom font loads, preventing 'flash of invisible text' (FOIT).next/fonthandles this by default.- Subset Fonts: Only include the characters you need from a font to reduce file size.
- Preload Critical Fonts: For your most important fonts, consider preloading them using
<link rel="preload">in your document's head.
Image Optimization Check
Which of the following are benefits of using the next/image component in a Next.js application?
Recap: Optimized for Performance
Great job! You've learned how to significantly boost your Next.js app's performance by optimizing images and fonts.
- Use
next/imagefor automatic image optimization, lazy loading, and layout shift prevention. - Leverage the
priorityprop for critical above-the-fold images. - Utilize
next/font/googleandnext/font/localfor efficient, self-hosted font loading, which also prevents layout shifts.
These practices lead to faster, more user-friendly applications.
常见问题解答
「图像与字体优化」课时是免费的吗?
是的 — 「图像与字体优化」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
「图像与字体优化」这节课中我会学到什么?
使用 `next/image` 优化图像,并高效管理字体以缩短加载时间。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack Web Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「图像与字体优化」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。