'How to make infinite scroll on Next.js static page?
I'm making portfolio using Next.js and count of projects on page is big enough. I want to start loading images when they get into the current viewport. Such scenario works well with default placeholder prop of next/image.
I'm using custom placeholder (skeleton) component for my images (placeholder is hided when runs onLoadingComplete image prop). If I used SSR then algorithm is clear but with SSG I've reached a dead end.
Will be happy to any advices!
My image component code:
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
/>
</>
);
};
Placeholder is just div with higher z-index.
Solution 1:[1]
You should consider using next/image
, which by default will only load images as they enter the viewport (you can control that via the lazyBoundary prop). SSG vs SSR does not affect this behavior.
Solution 2:[2]
You can simply add loading="lazy"
to your images. It is supported in modern browsers.
Update:
For videos you can use preload="none"
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Michael Flores |
Solution 2 |