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
ponents, 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>
ponents before they get added to the dom?
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
ponents, 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>
ponents before they get added to the dom?
- I am not very familiar with nextjs, but you could "prefetch" the images by appending them to the DOM as hidden. Then when they are all loaded, let nextjs do its stuff and the images should be displayed instantly as cached by the browser. – user3252327 Commented Sep 19, 2022 at 21:33
1 Answer
Reset to default 3Have you tried adding priority=true
to the Image ponent?
Read details here: next-image docs