Skip to content Skip to sidebar Skip to footer

Basic Infinite Scrolling/lazy Loading Blog Posts With Pure JavaScript

I'm looking for a lightweight solution (hopefully without jQuery but I'm open to suggestions) to 'lazy load' a long HTML page which is indexing tons of blog posts on the client-sid

Solution 1:

You probably need to add some attr to your #blog-post div. Like visible class or something else (Btw adding id to div which repeats is not a good idea. Your scripts will fail and will work for only first item, usually. You need to use class instead of id).

window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
      // you're at the bottom of the page
      // console.log("Bottom of page");

      var posts = document.querySelectorAll('.blog-post:not(.visible)');
      
      for(i = 0; i < posts.length; i++){
        if(posts[i] != undefined && i < 3){
            posts[i].className += "visible";          
        }  
      }
    }
};
.blog-post{
  /*display:none;*/
  opacity:0;
  transition: opacity 5s;
}

.visible{
  /*display:block !important;*/
  opacity:1;
}
<div class="blog-post visible">
      <h2 class="post-title">Cupcake ipsum.</h2>
      <img class="post-image" src="http://placehold.it/350x150">
      <p class="preview">Cupcake ipsum dolor sit. Amet bear claw marzipan tootsie roll.</p>
      <hr>
</div>
<div class="blog-post">
      <h2 class="post-title">Cupcake ipsum.</h2>
      <img class="post-image" src="img/posts/cupcakeIpsum.jpg">
      <p class="preview">Cupcake ipsum dolor sit. Amet bear claw marzipan tootsie roll.</p>
      <hr>
</div>
<div class="blog-post">
      <h2 class="post-title">Cupcake ipsum.</h2>
      <img class="post-image" src="img/posts/cupcakeIpsum.jpg">
      <p class="preview">Cupcake ipsum dolor sit. Amet bear claw marzipan tootsie roll.</p>
      <hr>
</div>

Scroll method taken from & tested: https://stackoverflow.com/a/31264162/2259466

Notes: Transition not worked as expected in my code. You need to use display none too but you can't use animation with it (You can actually, but need workaround). Or you can just use animations in js, harder way.

So in general code needs to look like it. I know it's not completed but I hope it gives you the idea of it.


Post a Comment for "Basic Infinite Scrolling/lazy Loading Blog Posts With Pure JavaScript"