简体   繁体   中英

How to load in data only one time when user scrolls to the bottom of the page?

I have a page that dynamically loads in HTML from a PHP script that scrapes another site for image links when the user scrolls to the bottom of the page. The issue is that it takes awhile for the script to complete and the function that detects that user has scrolled to the bottom of the page gets triggered several times and the HTML is loaded in several times causing duplicate sets of images. Is there a simple way to have javascript wait until the HTML is loaded before letting the function run again? The detection/load script looks like this:

$(window).scroll(function() {
    if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
        //alert("at the bottom.");
        $.post("function.php", function(data) {
            $('#wrap').append(data);
            });
    }
});

Thanks!

var loadAgain = true;
$(window).scroll(function() {
    if (loadAgain && $(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
        loadAgain = false;
        //alert("at the bottom.");
        $.post("function.php", function(data) {
            $('#wrap').append(data);
            loadAgain = true;
        });
    }
});

Set boolean status to make sure that the event is not fired more than once until it is complete. Like this:

    var loading = false;
    if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
        if (!loading) { 
            loading = true;
            $.post("function.php", function () {
                loading = false;
            })
        }
    }

Try this:

var loadFinished = true;
$(window).scroll(function() {
    if (loadFinished && ($(window).scrollTop() >= $(document).height() - $(window).height() - 10)) {
        //alert("at the bottom.");
        loadFinished = false;
        $.post("function.php", function(data) {
            $('#wrap').append(data);
            loadFinished = true;
        });
    }
});

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