17
loading...
This website collects cookies to deliver better user experience
<body>
<h1>Oberserver Intersection API</h1>
<div id="root"></div>
<div id="loading">Loading...</div>
<script src="script.js"></script>
</body>
div
element having id="root
.div
element having id="loading"
will be shown.fetchImage()
which when called fetches 5 images from the array of 20 images. Here, fetchImages()
can be any server API call.function fetchImage() {
if (imgCount !== 20) {
setTimeout(() => {
for (let i = imgCount; i < imgCount + 5; i++) {
const image = document.createElement("img");
image.src = data[i].src;
rootElement.append(image);
}
imgCount += 5;
}, 500)
}
}
Intersection Observer API
document.addEventListener("DOMContentLoaded", () => {
let options = {
root: null,
rootMargin: "0px",
threshold: 0.25
};
function handleIntersect(entries, observer) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
if (imgCount !== 20) {
fetchImage()
}
}
});
}
let observer = new IntersectionObserver(handleIntersect,
options);
observer.observe(loader);
})
We are calling InterectionObserver()
which takes two parameters, first one is a callback which would decide what will happen when intersection happens, second parameter is a set of options.
In options
, root
will be the element with which intersection occurs, by defining it as null means it will take window
by default. rootMargin
is just the CSS property for the root element. And threshold
can be an array of ratios which when passed can decide on what intersection ratio, the callback should be executed.
In handleIntersect()
, we are checking if the loader is intersected, then we are calling fetchImage()
to fetch 5 more images.
Atlast, we are calling the observer
to observe loader. That means we are targeting the loader, whenever it appears in the viewport, we will load 5 more images.
Intersection Observer API
, the callback will be fired only when the target element comes to the viewport which prevents the javascript engine to run unnecessary calls.