DEV Community

Ephraim Atta-Duncan
Ephraim Atta-Duncan

Posted on

Lazy Loading Images In Next.js

Introduction

We have all heard this term before. Lazy Loading. What is it anyways?

Lazy loading postpones the loading of resources on a page, in this case an image, until they are actually required. Rather than loading these resources as soon as the page loads, as is usually the case, they are delayed until the user need them. They have numerous advantages. We can make our web pages load really quickly with lazy loading. In this guide, we will cover how to lazy load images using Next.js.

Next.js comes default with an Image component. Lazy loading is enabled by default in the Next.js Image component. It is not only useful to the end-user, but it is also beneficial to the server because it does not have to execute image generation for images that may or may not be required.

Installation and Setup

You can create a new Next.js application using the following command:

npx create-next-app lazy-load-images
Enter fullscreen mode Exit fullscreen mode

Let's start the application by running the following command

npm run dev
# or
yarn dev
Enter fullscreen mode Exit fullscreen mode

We are running our application in the development server. Open your browser and navigate to https://localhost:3000.

Lazy Loading

Add a new image file to the public directory. In the pages directory, create a new file lazy-load.js. This will be our Next.js page.

Add the following to the fil

export default function ImagePage() {
    return (
        <h1>Image Page</h1>
    );
}
Enter fullscreen mode Exit fullscreen mode

Visit https://localhost:3000/lazy-load to preview the page. Now that the page has rendered succesfully, we can continue to implement lazy loading.

First import the Image component from Next.js

import Image from "next/image";
Enter fullscreen mode Exit fullscreen mode

Next, replace the <h1> tag with this the Image Component

<Image
  src="/github.jpg"
  alt="Github"
  width={600}
  height={450}
  layout="responsive"
  loading="lazy"
/>
Enter fullscreen mode Exit fullscreen mode

Now preview it in the browser to see the results. Add a lot of images and see lazy loading in action as you scroll.

Discussion (2)

Collapse
j471n profile image
Jatin Sharma

You don't even have to pass loading because next/image uses lazy loading as the default.

Collapse
dephraiim profile image
Ephraim Atta-Duncan Author

I realized this later on that it was baked into Next Image by default.