Blog>
Snippets

Parallel image optimization

Leverage Next.js Image component with `srcset` attribute to asynchronously load multiple image resolutions in parallel for optimized responsive images.
import Image from 'next/image';

function ResponsiveOptimizedImage() {
  return (
    <div>
      <Image
        src="/path/to/image.jpg" // The base image path
        sizes="(max-width: 750px) 100vw, (max-width: 980px) 50vw, 33vw" // Define responsive image sizes
        srcSet={`
          /path/to/image_small.jpg 750w,  // Define different image paths for different resolutions
          /path/to/image_medium.jpg 980w,
          /path/to/image_large.jpg 1440w
        `}
        width={1440} // Specify the width of the largest image
        height={900} // Specify the height of the largest image, maintaining the aspect ratio
        alt="A description of the image"
        layout="responsive" // Layout responsive adjusts the image size dynamically
      />
    </div>
  );
}

export default ResponsiveOptimizedImage;
This code snippet imports the Next.js Image component and defines a functional React component 'ResponsiveOptimizedImage'. Within the component, the 'Image' is used to load a base image and then specify alternate image resolutions using the 'srcSet' attribute. The 'sizes' attribute defines how wide the image is in different viewport conditions which instructs the browser to select the appropriate image resolution from the 'srcSet'. The 'layout' attribute set to 'responsive' ensures the image scales with the viewport. This allows for parallel optimized image loading based on the client's viewport and device resolution.