1

I'm trying to load all the images before removing the LOADING SCREEN using this code. The loading works and it goes away when all the images are loaded, But When I try to use the images as background for a div, it takes time to load it again. I'll appreciate your advice

pages/index.tsx:

export default function Home() {
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    const images = [
      "/images/homePage/main-illustration.webp",
      "/images/homePage/title-logo-text.webp",
      "/images/homePage/title-logo-gear.webp"
    ];
    let loadedCount = 0;

    const checkIfAllLoaded = () => {
      loadedCount++;
      if (loadedCount === images.length) {
        setIsLoaded(true);
      }
    };

    images.forEach((src) => {
      const img = new Image();
      img.onload = checkIfAllLoaded;
      img.src = src;
    });
  }, []);

  return (
    <>
        {!isLoaded && (
          <div>
            Loading...
          </div>
        )}
      {isLoaded && (
        <>
          <Navbar />
          <HomePage />
          <Footer />
        </>
      )}
    </>
  );
}

components/Hero.tsx

const Hero = () => {
  return (
    <div className="bg-[url(/images/homePage/main-illustration.webp)] bg-cover">    
    </div>
  );
};

export default Hero;
  • 1
    Do any of the tecniques suggested in https://stackoverflow.com/questions/1373142/preloading-css-images help? – A Haworth Mar 16 '23 at 09:37
  • @AHaworth The mentioned solutions didn't work. I checked the network tab and the images are getting loaded twice. So the preloading seems to have no effect when I actually use the images later as background for div – Farhad Faraji Mar 16 '23 at 10:11
  • So even the suggestion that you load them off-screen as backgrounds didn't work? (I can see why loading them as img elements might not work). – A Haworth Mar 16 '23 at 11:23
  • @AHaworth I checked all the methods and only the first one "Preloading images using CSS only" seems to work. So I create a div for every value inside my array and set the mentioned style to it, and then I append the div to the body. Thanks again for the help – Farhad Faraji Mar 19 '23 at 10:43

0 Answers0