rad182
rad182

Reputation: 85

Preload image urls using new Image()

I'm trying to preload or prefetch remote images in my photo gallery but it seems that new Image() conflicts with the nextjs's next/image.

This code works fine before(using CRA) I migrated to nextjs.

 const img = new Image();
 img.src = photoToPreload.largeUrl;

Any suggestion is very much appreciated.

Upvotes: 1

Views: 6336

Answers (3)

Gabriel Linassi
Gabriel Linassi

Reputation: 541

To prefetch new images of the Carousel, you can render an invisible Image component with the src of the next image and NextJS will preload it to you and will be ready when the user swipe to the next slide. If your carousel is above-the-fold, make sure to add priority to the first slide also.

import NextImage from 'next/image'
() => {
  return (
    <div className="relative w-[300px]">
      <NextImage
        src={Screens[activeScreenIdx]}
        placeholder="blur"
        quality={100}
        layout="fill"
        objectFit="contain"
        sizes="350px"
      />
    {/* prefetch next image */}
      <NextImage
        {/* ..% Screen.length to avoid going out boundary */}
        src={Screens[(activeScreenIdx + 1) % Screens.length]}
        placeholder="blur"
        className="invisible" {/* just for preloading purposes */}
        quality={100}
        layout="fill"
        objectFit="contain"
        sizes="350px"
      />
    </div>
 )
}

Upvotes: 1

Mark G
Mark G

Reputation: 2206

You can try giving Next.js's version of Image a nonconflicting alias (or the other way around with your custom Image import):

// CommonJS style
const { default: NextImage } = require("next/image");
// ES module style
import NextImage from "next/image";

// alternatively
import { default as NextImage } from "next/image";

Upvotes: 1

Nick Vu
Nick Vu

Reputation: 15520

You can change imported name of next/image to another name like

import NextImage from 'next/image'

That would help you to reserve the name Image for your original stuff

But I think you can achieve the same thing with next/image in a better way

You just add priority prop to your NextImage

<NextImage {...otherProps} priority={true}/>

It will generate preload link to preload your image as an important resource. Furthermore, you can leverage other optimization stuff in next/image package.

Upvotes: 2

Related Questions