'Can I preload an image for a component before it gets used in nextjs
I'm close to deploying a project with NextJS, however I noticed that a lot of the images take quite a bit of time to appear on screen.
I've installed sharp and set the priority to true, but even then images appear pretty slowly.
There's one part of the application, where a specific component gets conditionally rendered. That component has a small illustration included (about 30-50kb depending on the type) and it only shows for 2 seconds, since it's a short confirmation for the user.
There's also another page, which has a bigger illustration on it (about 500kb), which I would love to preload, since it takes a good second to load, when the component gets rendered.
Basically what I'd like to do, is fetch the needed images/illustrations ahead of time, before they need to be used, so that they appear instantaneously for the user.
Is there a way to do this in NextJS? Also happy to move away from the Next/Image component and just use img tags to do this.
Not sure whether code helps in this case, but here is how I display the 500kb image:
<div className="result__illustration">
<Image
src={resultIllu}
alt=""
layout="responsive"
objectFit="contain"
priority={true}
/>
</div>
Solution 1:[1]
This is possible using new Image() and then adding an src attribute to it. I made a simple example to illustrate a memoized version of this behavior:
const PreloadedImage = preloadImage("https://via.placeholder.com/700x500");
export default function App() {
return (
<div className="App">
<PreloadedImage alt="Placeholder image" />
</div>
);
}
function preloadImage(src) {
const image = new Image();
image.src = src;
return function PreloadedImage(props) {
return <img {...props} src={src} />;
};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Undo |
