Reputation: 4562
Ignoring the fact that this is generally considered a bad practice, I'm trying to understand how I can preload a set of images either before a page transition or prior to rendering my page. My use case requires quite a few large image files to be displayed at the same time and animated onto the screen. I'd like to essentially have a loading spinner on the page while the initial set of large images is downloaded and cached in the browser and then I can show them all at once.
If I want to do this with standard react, I can do something like this:
await Promise.all(
images.map(async (url) => {
return new Promise((resolve) => {
const image = new Image();
image.src = url;
image.onload = () => resolve(true);
});
})
)}
And then have an isLoading
boolean get flipped when everything is done loading. With the nextjs Image
components, though, I can't load those initial images until they are actually added to the dom. The URL for those images changes based on various conditions so I can't really use the original solution to preload them.
Is there a way to force the browser to download the image sources generated from my nextjs <Image>
components before they get added to the dom?
Upvotes: 0
Views: 7759
Reputation: 181
Have you tried adding priority=true
to the Image component?
Read details here: next-image docs
Upvotes: 3