There are numerous approaches to accomplish this task.
Personally, I prefer utilizing the Intersection Observer API
.
This API enables you to execute a callback function when an element enters the viewport.
According to the documentation, here are some common use cases:
- Lazy-loading images or content as a user scrolls through a webpage.
- Implementing endless scrolling websites where content loads continuously as the user scrolls.
- Monitoring ad visibility for revenue calculations.
- Determining whether to initiate tasks or animations based on user visibility.
The Intersection Observer API triggers the callback when either of these conditions is met:
- An element intersects with the viewport or a specified root element.
- The observer starts watching a target element for the first time.
let options = {
root: document.querySelector('#scrollArea'),
rootMargin: '0px',
threshold: 1.0
}
let observer = new IntersectionObserver(callback, options);
// Alternatively
var intersectionObserver = new IntersectionObserver(function(entries) {
if (entries[0].intersectionRatio <= 0) return;
loadItems(10);
console.log('Loaded new items');
});
intersectionObserver.observe(document.querySelector('.scrollerFooter'));
I have developed a small npm package specifically for lazy loading functionality.
https://www.npmjs.com/package/dyno-img-react
This package displays a low-resolution image until the user reaches the specified intersection area, at which point it fetches and displays the high-quality image before removing the observer.
If you are working with React Native, I recommend checking out this library:
react-native-intersection-observer
You can find the implementation details in the following code snippet:
https://github.com/zhbhun/react-native-intersection-observer/blob/master/src/IntersectionObserver.ts
This library utilizes the onLayout event internally for management.
import { IOScrollView, InView } from 'react-native-intersection-observer'
const Component = () => (
<IOScrollView>
<InView onChange={(inView: boolean) => console.log('Inview:', inView)}>
<Text>Plain children are always rendered. Use onChange to monitor state.</Text>
</InView>
</IOScrollView>
)
export default Component