jQuery $.get 冻结执行

jQuery $.get freezing on execute

本文关键字:执行 冻结 get jQuery      更新时间:2023-09-26

我有以下脚本执行"无限滚动"样式的功能:

    var next_page_link = $('.wp-pagenavi a:eq(-2)').attr('href'); 
    $(window).scroll(function() {
        if ($(window).scrollTop()  > $(document).height() / 2) {
            $.get(next_page_link, function(data){
                    if ($(data).find('.wp-pagenavi a:eq(-2)').attr('href') != next_page_link) {
                        next_page_link = $(data).find('.wp-pagenavi a:eq(-2)').attr('href');
                        var content = $(data).find('#multiple_product_top_container').html();
                        $('#multiple_product_top_container').append(content);
                    }
            });                 
        }
    });

我遇到的一个问题是,每次$.get函数运行时,浏览器都会冻结 2-3 秒或更长时间,并且只有在下一页完全加载时才解冻。

我的问题是,是否可以将$.get函数设置为异步运行或其他可以消除冻结的方法?

顺便说一句,我知道可以使用服务器端脚本,但我遇到了很多冲突,而且涉及更多解析会更复杂。

谢谢

评论中问题的答案:How do I set it so that a new request can't happen until the old one finishes?

您使用信号量:

var semaphore = true;
var next_page_link = $('.wp-pagenavi a:eq(-2)').attr('href'); 
$(window).scroll(function() {
    if ($(window).scrollTop()  > $(document).height() / 2 && semaphore) {
        semaphore = false;
        $.get(next_page_link, function(data){
            semaphore = true;
                if ($(data).find('.wp-pagenavi a:eq(-2)').attr('href') != next_page_link) {
                    next_page_link = $(data).find('.wp-pagenavi a:eq(-2)').attr('href');
                    var content = $(data).find('#multiple_product_top_container').html();
                    $('#multiple_product_top_container').append(content);
                }
        });                 
    }
});
最好

添加一个条件,即当您已经检索到所有可能检索的内容时,不会发出新的请求。