I am in the process of creating a portfolio using Next.js and have a large number of projects on the page. I would like to implement a feature where images start loading only when they enter the current viewport. This functionality works well with the default placeholder prop of next/image.
Currently, I am using a custom placeholder (skeleton) component for my images, which is hidden once the onLoadingComplete image prop runs. Although I understand the algorithm for server-side rendering (SSR), I have hit a roadblock with static site generation (SSG).
I would greatly appreciate any advice or suggestions!
The code for my image component:
import Placeholder from './placeholder';
const ImageRenderer = ({ url, alt, layout, objFit, width, height }) => {
const [isImageLoaded, setIsImageLoaded] = useState(false); // loading state
return (
<>
{!isImageLoaded && <Placeholder />}
<StyledImage
src={url}
alt={alt}
width={width}
height={height}
layout={layout}
objectFit={objFit}
onLoadingComplete={() => setIsImageLoaded(true)} // runs when next/image is loaded
/>
</>
);
};
The placeholder is simply a div with a higher z-index.