/ Gists / Infinity loading
On gists

Infinity loading

JavaScript ES 6

Infinity loading.js Raw #

/* OLD */
let currentPage = 1;
let totalPages = 5;

window.addEventListener('scroll', function() {
  // Check if the user has reached the bottom of the page
  if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
    // Check if there are more pages to load
    if (currentPage < totalPages) {
      // Fetch the data
      await fetch('url')
      currentPage++
    }
  }
});


/* NEW */
/* https://javascript.plainenglish.io/you-dont-need-using-scroll-event-to-load-data-infinite-b893c46a84ea */
let isVisible = false;
// the element visible / unvisble will trigger the function.
const observer = new IntersectionObserver(entries => {
  isVisible = entries[0].isIntersecting
  if (entries[0].isIntersecting) {
      // load new content
      loadData().then(() => {
         setTimeout(() => {
           // if the loading element still visible means the list height is less than container
           // so try to load more
           isVisible && loadData()
         }, 100)
      })
   }
});

observer.observe(document.querySelector('.more')