Reputation: 1118
I have a Gallery component in React. I have 40 image URLs and by default, I only show 10, by mapping 10 URLs (in items
I always put the exact amount of "images" that need to be rendered):
{items.map((item, index) => {
return (
<img
key={index}
src={item.src}
alt={item.alt}
/>
);
})}
My question is, how do I preload 4 more images (that are only going to be shown if clicked on "show more")?
I found this very helpful StackOverflow post that seems to tackle this very issue. So in my current implementation, I have something like this:
for (let i = 0; i < 10 + numberOfExtraPrelodedImages; i++) {
const item = galeryItems[imageLoadedAndCount.count + i];
if (item?.url) {
new Image().src = item.url;
}
}
My only concern is that now when in the img
tag I "recall" the URL doesn't that send a now API request to "get the latest content"? Or does it use the preloaded content from the code shown above? Is this the correct way to preload images in React?
Upvotes: 2
Views: 581