guang-comments.js 1.61 KB
/*
 * @Author: Targaryen
 * @Date: 2017-05-25 14:36:33
 * @Last Modified by: Targaryen
 * @Last Modified time: 2017-06-02 10:51:56
 */
const $ = require('yoho-jquery');
const article_id = $('#guangDetail').data('id');
const $comments = $('#comments');

let page = 1;
let beforeScroll = document.body.scrollTop; // 滚动前位置记录
let onLoading = false; // 是否正在加载
let loadingEnd = false;

/**
 * 异步加载评论
 */
const getComments = () => {
    if (loadingEnd) {
        return false;
    }

    if (!onLoading) {
        onLoading = true;
    } else {
        return false;
    }

    $.ajax({
        type: 'get',
        url: '//m.yohobuy.com/guang/info/getComments',
        data: {
            article_id: article_id,
            page: page++
        },
        success: function(result) {
            let noResult = !result || result.length < 1;

            if (noResult) {
                loadingEnd = true;
                return false;
            }

            $comments.append(result);
            onLoading = false;
        }
    });
};

/**
 * 当scroll到1/2$goodsContainer高度后继续请求下一页数据
 */
const scrollHandler = function() {
    if ($(window).scrollTop() > $('#guangDetail').height() * 0.6) {
        getComments();
    }
};

/**
 * 滚动加载
 */
$(window).scroll(function() {
    setTimeout(function() {
        let afterScroll = document.body.scrollTop;

        if (afterScroll - beforeScroll > 0) {
            window.requestAnimationFrame(scrollHandler);
            beforeScroll = afterScroll;
        } else {
            return false;
        }
    }, 5);
});

getComments();