Refactored code for infinite scrolling