Simple Infinite Scroll with PURE Javascript (Free Download)

Welcome to a tutorial on how to create an infinite page scroll with vanilla Javascript. If you have been following up with social media – Facebook, Twitter, Instagram, etc… Then you should not be a stranger to that “scroll down to load more contents” interface. Yep, that is exactly what we will walk through in this guide – An example of infinite scroll using only pure Javascript. Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

TABLE OF CONTENTS

 

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • If not using PHP, change endless.url in 2-iscroll.js section A to your own server-side script.
  • Launch 1-iscroll.html in the browser. Captain Obvious – Use http:// not file://.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

JAVASCRIPT INFINITE SCROLL

All right, let us now get into the steps of creating a simple endless scroll with Javascript.

 

STEP 1) CONTENT PAGE

1-iscroll.html
<!-- (A) CONTENTS WRAPPER -->
<div id="page-content"></div>
 
<!-- (B) JUST SOME COSMETICS FOR DEMO -->
<style>
#page-content { background: lightblue; }
.page-demo { height: 1600px; }
</style>

That’s all, as straightforward as can be. We only need a <div id="page-content"> wrapper to load the contents into.

 

 

STEP 2) INFINITE SCROLL JAVASCRIPT

2A) FLAGS & SETTINGS

2-iscroll.js
var endless = {
  // (A) PROPERTIES & FLAGS
  url : "3-dummy.php", // change this to your own!
  first : true,        // loading first page?
  proceed : true,      // ok to load more pages? "lock" to prevent loading multiple pages
  page : 0,            // current page
  hasMore : true,      // has more content to load?
  // ...
}

All the infinite scroll mechanics are contained within the var endless object. Right at the top, we have a bunch of “control flags”… Will explain why these are useful below.

 

2B) INITIALIZE INFINITE SCROLL

2-iscroll.js
// (B) INITIALIZE INFINITE SCROLL
init : () => {
  // (B1) LISTEN TO END OF PAGE SCROLL - LOAD MORE CONTENTS
  window.addEventListener("scroll", () => {
    if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) { endless.load(); }
  });
 
  // (B2) LOAD INITIAL PAGE
  endless.load();
}
window.addEventListener("DOMContentLoaded", endless.init);

init() loads on DOM content ready, and initializes the endless scroll.

  • (B1) Attach a page scroll listener to the window, run endless.load() when the hits the bottom of the page.
  • (B2) Run endless.load() itself to load the first page from the server.

 

2C) AJAX LOAD CONTENT

2-iscroll.js
// (C) AJAX LOAD CONTENT
load : () => { if (endless.proceed && endless.hasMore) {
  // (C1) ENSURE ONLY 1 PAGE CAN LOAD AT ONCE
  endless.proceed = false;

  // (C2) PAGINATION & POST DATA
  var data = new FormData(),
      nextPg = endless.page + 1;
  data.append("page", nextPg);
  // data.append("KEY", "VALUE");
 
  // (C3) AJAX FETCH CONTENT
  fetch(endless.url, { method:"POST", body:data })
  .then(res => res.text())
  .then(res => {
    // (C3A) NO MORE CONTENT
    if (res == "END") { endless.hasMore = false; }

    // (C3B) APPEND CONTENT INTO HTML WRAPPER
    else {
      var el = document.createElement("div");
      el.innerHTML = res;
      document.getElementById("page-content").appendChild(el);
      endless.proceed = true; // unlock
      endless.page = nextPg;  // update current page

      // (C3C) FIRST PAGE ONLY - MAKE SURE CONTENT COVERS WINDOW HEIGHT
      if (endless.first) {
        if (document.body.scrollHeight <= window.innerHeight) { endless.load(); }
        else { endless.first = false; }
      } else { endless.first = false; }
    }
  });
}}

Dumb trolls should be thinking “just fetch the contents, this is so complicated and stupid”. Feel free to do it your way, learn the hard way. All of the below have been contributed by people over time – You will run into the same problems, and implement all of these in one way or another.

AJAX is asynchronous. Impatient users will scroll down and up many times, resulting in a dozen parallel page loads. To make sure only one-page loads at a time, we introduce the endless.proceed flag.
  • (C) Proceed with loading only when the flag is true – load : () => { if (endless.proceed && endless.hasMore).
  • (C1) “Lock” the function once it starts – endless.proceed = false.
  • (C3B) “Unlock” after the current fetch has ended – endless.proceed = true.
“Infinite scroll” sounds nice, but devices have limited memory. To prevent an “overloaded page”, pagination and limits have to be set in place.
  • To keep track of the number of pages loaded, we introduce endless.page and endless.hasMore.
  • (C2) Calculate next page to load nextPg = endless.page + 1, send it to server – data.append("page", nextPg).
  • (C3B) Update the current page on load – endless.page = nextPg.
  • (C3A) The server should respond with END when there is no more content to serve – We set endless.hasMore = false to prevent load() from firing.
There will be a problem when the first-page load is not “tall enough” – The user cannot scroll down to the bottom to load more.
  • (C3C) Basically, we detect the height of the content on the first loading cycle endless.first. Load until the content reaches the bottom of page.

 

 

STEP 3) SERVER-SIDE CONTENT

3-dummy.php
<?php
// (A) NO MORE CONTENT TO SERVE
if ($_POST["page"]==5) { echo "END"; }

// (B) SERVE DUMMY PAGE
else { echo "<div class='page-demo'>PAGE ".$_POST["page"]."</div>"; } ?>

Lastly, this is just a dummy server-side script – Output whatever content you are working on, with whatever language you are using. Things to take note of:

  • The Javascript will POST a page over, use this to do pagination as required.
  • Output END if there is nothing left to show.

 

 

EXTRA BITS & LINKS

That’s the end of the tutorial, and here are a few extras that you may find useful.

 

COMPATIBILITY CHECKS

Should not run into any compatibility issues with all modern browsers.

 

NOTE – BAD FOR SEO

Also, a piece of bad news for you SEO lovers. Even though some search engines are smart enough to understand AJAX calls, they may not “scroll down” to load more content; Infinite scrolling is only good for certain types of content, and please do not use it to “hide” your useful content… For example, “scroll down to read more” for an article. You will end up on the bad side of SEO practice.

 

TUTORIAL VIDEO

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to build a better project, and if you have anything to add to this guide, please feel free to comment below. Good luck and happy coding!

14 thoughts on “Simple Infinite Scroll with PURE Javascript (Free Download)”

  1. Nice tutorial!
    I’ve tried the script: it works perfectly on Firefox, while on Chrome 49 and Opera 36 (I need to support old browsers) only initial contents are loaded and nothing happens when I scroll the page. I don’t know why.

    1. It’s clear that it depends on “listen” function.
      I’m using the following code (it works with every browser I’ve tested it):

      listen: function() {
      if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
      endless.load();
      }
      };

    2. Thanks for sharing! documentElement, offsetHeight, scrollTop should be well-supported from IE 8 and onwards… So anyone who is working with the ancient browsers – Take note.

  2. Thanks,
    After doing lots of googling. At last I came to a solution to give a try. I have read and understood this post bro. I typically think this is the way to go given the fact impressive design is a big part of user satisfaction in this day and age.

Leave a Comment

Your email address will not be published. Required fields are marked *