如何轻松提升你的Next.js 14网站速度,这对你的SEO排名很重要!

212 阅读3分钟

大家好,我是梦兽。一个 WEB 全栈开发和 Rust 爱好者。如果你对 Rust 非常感兴趣,可以关注梦兽编程公众号获取群,进入和梦兽一起交流。

页面速度是搜索引擎的一个重要排名因素。Next.js提供了多种功能来提高你的网站加载时间,包括自动代码分割、使用next/image组件优化的图片加载,以及增量静态生成(ISR),用于更新静态内容而无需重建整个站点。这些功能不仅提升了你的SEO,还显著改善了用户体验,从而提高了用户参与度和转化率。

Next.js提供了我们加速网站所需的一切。由于图片对Web核心指标(如LCP等)有很大影响,我们从图片传输开始优化。

将图片修改成webp格式

Next.js 14默认使用Webp格式的图片,如果我们使用内置的next/image包。在我们的next.config.js文件中,我们也添加Avif格式。正如你所看到的,我们屏蔽了“images.ctfassets.net”这个域名,因为我们在示例中使用了Contentful作为内容管理系统。

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    formats: ["image/avif""image/webp"],
    remotePatterns: [
      {
        protocol: "https",
        hostname: "images.ctfassets.net",
        pathname: "**",
      },
    ],
  },
};

module.exports = nextConfig;

图片格式/大小:SEO成功的关键

随着大多数网络流量来自移动设备,确保你的Next.js网站对移动设备友好是毫无疑问的。响应式设计、快速加载时间和触控友好的导航是关键元素。Next.js的内置功能支持这些要求,使得创建在桌面和移动平台上都表现良好的网站变得更加简单。 我们使用Next.js 14引入的新功能“getImageProps”来启用srcset / picture标签的使用来适配不同设备。 这是我们将要封装的图片组件。

import NextImage, { ImageProps as NextImageProps } from "next/image";
import { getImageProps } from "next/image";
import { twMerge } from "tailwind-merge";

import { ImageFieldsFragment } from "@/lib/__generated/sdk";

interface ImageProps extends Omit<ImageFieldsFragment"__typename"> {
  nextImageProps?: Omit<NextImageProps"src" | "alt">;
}

export const CtfPicture = ({
  url,
  width,
  height,
  title,
  nextImageProps,
}: ImageProps) => {
  if (!url || !width || !height) return null;

  // common option
  const common_high = {
    alt: title || "",
    width: width,
    height: height,
    priority: nextImageProps?.priority,
    classNametwMerge(nextImageProps?.className"transition-all"),
  };
  const common_medium = {
    alt: title || "",
    width800,
    height500,
    classNametwMerge(nextImageProps?.className"transition-all"),
  };

  const common_low = {
    alt: title || "",
    width300,
    height200,
    classNametwMerge(nextImageProps?.className"transition-all"),
  };

  // Pass common as an argument with src in getImageProps and destructure the output.
  const {
    props: { srcSet: high },
  } = getImageProps({
    ...common_high,
    src: url,
    priority: nextImageProps?.priority,
  });

  const {
    props: { srcSet: medium },
  } = getImageProps({
    ...common_medium,
    src: url,
    priority: nextImageProps?.priority,
  });

  const {
    props: { srcSet: low, ...rest },
  } = getImageProps({
    ...common_low,
    src: url,
    priority: nextImageProps?.priority,
  });

  return (
    <picture>
      <source media="(max-width: 740px)" srcSet={low} />
      <source media="(max-width: 980px)" srcSet={low} />
      <source media="(min-width: 1280px)" srcSet={medium} />
      <source media="(min-width: 1480px)" srcSet={high} />
      <img alt={title || ""} {...rest} />
    </picture>
  );
};

使用它!! featuredImage属性是url width height的集合

(
<div className="flex-1 basis-1/2">
        {article.featuredImage && (
          <CtfPicture
            nextImageProps={{
              className: "w-full",
              priority: true,
              sizes: undefined,
            }}
            {...article.featuredImage}                
          />
        )}
      </div>
)

为picture标签定义“srcset”

我们定义了三种不同大小的srcSet,并结合媒体查询使用它们。根据最大宽度,我们使用不同的srcSet,因此使用不同的图片尺寸。浏览器可以选择最适合的尺寸。

return (
    <picture>
      <source media="(max-width: 740px)" srcSet={low} />
      <source media="(max-width: 980px)" srcSet={low} />
      <source media="(min-width: 1280px)" srcSet={medium} />
      <source media="(min-width: 1480px)" srcSet={high} />
      <img alt={title || ""} {...rest} />
    </picture>
  );

注意

感谢阅读!感谢您的时间,并希望您觉得这篇文章有价值。在您的下一个 JavaScript 项目中尝试使用柯里化,并在下面的评论中告诉我它如何改善了您的编码体验!

创建和维护这个博客以及相关的库带来了十分庞大的工作量,即便我十分热爱它们,仍然需要你们的支持。或者转发文章。通过赞助我,可以让我有能投入更多时间与精力在创造新内容,开发新功能上。赞助我最好的办法是微信公众号看看广告。

本文使用 markdown.com.cn 排版