How to do infinite scrolling with javascript only without jquery

前端 未结 6 1080
日久生厌
日久生厌 2021-02-01 10:13

I wish to implement infinite scrolling with javascript and without jquery.

I am new to javascript.

After searching all over the net, I have this code.

         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 11:13

    I use requestAnimationFrame instead of listening for scroll. I also added a throttle based on time so it doesn't overwork our page and batched the element additions:

    var numElementsToAdd = 10,
        offsetForNewContent = 20;
    
    function checkInfiniteScroll(parentSelector, childSelector) {
      var lastDiv = document.querySelector(parentSelector + childSelector),
          lastDivOffset = lastDiv.offsetTop + lastDiv.clientHeight,
          pageOffset = window.pageYOffset + window.innerHeight;
    
      if(pageOffset > lastDivOffset - offsetForNewContent ) {
        for(var i = 0; i < numElementsToAdd; i++) {
          var newDiv = document.createElement("div");
          newDiv.innerHTML = "my awesome new div";
          document.querySelector(parentSelector).appendChild(newDiv);
        }
        checkInfiniteScroll(parentSelector, childSelector);
      }
    };
    
    var lastScrollTime = Date.now(), 
        checkInterval = 50;
    
    function update() {
      requestAnimationFrame(update);
    
      var currScrollTime = Date.now();
      if(lastScrollTime + checkInterval < currScrollTime) {
        checkInfiniteScroll("#scroll-content", "> div:last-child");
        lastScrollTime = currScrollTime;
      }
    };
    
    update();
      #scroll-content > div {
          background: #c0c0c0;
          height: 40px;
          margin-bottom: 5px;
      }
    test div

    Demo

提交回复
热议问题