I am trying to preload images and set them as background in the React HOC component, but despite loading it the css is calling and caching the Images again.
interface ImagePreloaderProps {
pictures: string[];
interval?: number;
children?: React.ReactNode;
}
const ImagePreloader: React.FC<ImagePreloaderProps> = ({ pictures, interval = 3000, children }) => {
const [currentIndex, setCurrentIndex] = useState(0);
const [imagesLoaded, setImagesLoaded] = useState(false);
console.log('vhdc in the ImagePreloader', imagesLoaded);
useEffect(() => {
const preloadImages = async () => {
const promises = pictures.map((url) => {
return new Promise((resolve) => {
const img = new Image();
img.src = url;
img.onload = () => resolve(img);
});
});
try {
await Promise.all(promises);
setImagesLoaded(true);
} catch (error) {
console.error('Error preloading images:', error);
}
};
preloadImages();
}, [pictures]);
useEffect(() => {
const intervalId = setInterval(() => {
setCurrentIndex((prevIndex) => (prevIndex + 1) % pictures.length);
}, interval);
return () => clearInterval(intervalId);
}, [pictures, interval]);
const imageContainers = pictures.map((url, index) => (
<div
key={url}
style={{
backgroundImage: `url(${url})`,
width: '100%',
height: '100%',
backgroundSize: 'cover',
display: index === currentIndex ? 'block' : 'none',
}}
>
{children}
</div>
));
return <>{imagesLoaded && imageContainers}</>;
};
Following the screenshots of the network Tab where I have already preloaded images it is called again by css as other initiator.
Please Refer to the following Img Network calls.