0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · 课时

图像与字体优化

利用 Next.js 内置的图像和字体组件实现自动优化,提升加载性能。

图像与字体优化 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack (App Router + Server Actions) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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 alt attributes.

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/image component offers automatic optimization, lazy loading, and CLS prevention.
  • The next/font module 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!

常见问题解答

「图像与字体优化」课时是免费的吗?

是的 — 「图像与字体优化」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack (App Router + Server Actions) 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。

「图像与字体优化」这节课中我会学到什么?

利用 Next.js 内置的图像和字体组件实现自动优化,提升加载性能。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack (App Router + Server Actions) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「图像与字体优化」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Next.js 15 Fullstack (App Router + Server Actions) 课中编写并运行代码吗?

能。每节 Next.js 15 Fullstack (App Router + Server Actions) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 图像与字体优化
  2. 捆绑包大小分析
  3. 高级缓存策略
  4. 使用 Suspense 与加载状态实现界面流式传输
← 返回 Next.js 15 Fullstack (App Router + Server Actions)