简体   繁体   中英

How to load more content with ajax when user scrolls to the bottom the of page only once

I want to append an html file I have to a div when the user scrolls to the bottom of the page. But I only want to do this once. I managed to write a script that works, but I noticed after a few refreshes of the page, it randomly retrieves and appends the HTML more than once. Notice, I'm using a Boolean to control the script to one use,I have a hunch this might be where my problem resides.

This is my script and div that will have content appended to it:

** EDIT: removed the if (used == false) since its unnecessary. **

 var used = false; $(window).scroll(function () { if ($(window).scrollTop() >= $(document).height() - $(window).height() - 400 && used == false) { $.get("more.html",function(data){ $("#new-content").append(data); used = true; }); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="new-content"> </div> 

This is the html I want to append

    <div class="double-wrapper">
     <div class="app">
      <div class="app-inner"></div>
     </div>
     <div class="app">
      <div class="app-inner"></div>
     </div>
    </div>
    <div class="inn">
     <div class="inn-inner">
     </div>
    </div>

Here is the example. By using a second boolean to lock the function before any asynchronous call is made, you can keep the original one used to keep track that the content has been added successfully. If there is an error in the request (you can try to change the URL by an invalid one), used will stay at false and the function can try again the request (i added an error function to release the lock).

  var used = false, locked = false; $(window).scroll(function () { //I shortened conditions (for a boolean, "!used" is same as "used == false") if ($(window).scrollTop() >= $(document).height() - $(window).height() - 400 && !used & !locked) { //lock function before the call locked = true; $.get("http://date.jsontest.com",function(data){ //different injection for the test because i used JSON test content //$("#new-content").append(data); $("#new-content").html($("#new-content").html() + '<p>' + JSON.stringify(data) + '</p>'); used = true; //release the lock when results arrive locked = false; }).fail(function(){ console.log('request has failed'); //release the lock on error if you want to be able to try the request again locked = false; }); } }); 
 body{ height: 1000px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="new-content"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM