Blog>
Snippets

Lazy Loading Offscreen Images with Next.js

Implement lazy loading in Next.js by setting the 'loading' attribute to 'lazy' in the Image component to defer loading of images until they are in or near the viewport.
import Image from 'next/image';

// Lazy load an offscreen image using Next.js Image component
function MyImageComponent() {
  return (
    <div>
      <Image
        src='/path/to/image.jpg' // Path to your image
        alt='Descriptive text for the image'
        width={500} // Width of the image in pixels
        height={300} // Height of the image in pixels
        loading='lazy' // Enables lazy loading
      />
    </div>
  );
}

export default MyImageComponent;
This snippet of code imports the Image component from Next.js and demonstrates how to use it with the 'loading' attribute set to 'lazy'. This ensures that the image will only start loading when it's near the viewport, which can improve page performance.