Infinite Scrolling
- kwangjin baek
- Nov 26, 2022
- 2 min read
Updated: Nov 27, 2022

When developing a website there comes an occasion when you want to manipulate scroll events not just to add fabulous effects on your site to look cooler but to improve the performance of your site. Infinite scrolling can improve performance by requesting a small amount of data at a time. I am going to show you one way of implementing the feature.
List of Contents
What we need
How it is done
Code Example
Conclusion
What we need
A pixel value from the top left corner of the window | |
The height of the screen | |
Actual content height | |
Catches a scroll event on a given element |
How to do it
To catch the moment when a user hits the bottom (or desired point where you want the function to fire). We need, first, to know how far a user scrolled down from the top of the screen. To get this we are going to use window.scrollY
Then we need to know how big the content actually is, to get this value let's use document.body.offsetHeight
But comparing the two values won't do anything as the scrolling value cannot come close to the offset height value of the body element, let alone exceeds it

So one way to come around this is simply to deduct a certain value from the offset Height (or the other way around). However, there is a fancier way to do the same thing. Here we are going to use window.innerHeight
Code Example
window.addEventListener('scroll', () => {
const innerHeight = window.innerHeight
const scrollY = window.scrollY
const bodyHeight = document.body.offsetHeight
if (innerHeight + scrollY > bodyHeight) {
fetchPhotos() // desired function
}
})Conclusion
Infinite scrolling not only does look fancy but also improves performance by making a request when it is needed to get the right amount of data to reduce the loading time. So why don't we maximize the usage of this feature to improve our user's experiences?

Comments