监听滚动事件懒加载数据

回到文章
<div class="container"></div>
.item {
    min-height: 80px;
    border-bottom: 1px solid #cccccc;
}
.last {
    background-color: #f4d0f9;
}
let data = [];
for(let i=0, len=10000; i<len; i++) {
    data.push({
        index: i,
        score: (Math.random()+'').substr(-8)
    });
}
// 创建某一页的数据,然后追加到DOM中
function createDom(start, count) {
    let div = document.createDocumentFragment();
    for(let i=start, len=start+count; i<len; i++) {
        let item = document.createElement('div');
        item.className = 'item';

        let html = `<p>${data[i].index}楼:</p><p>${data[i].score}</p>`;
        if (i===len-1) {
            item.className = 'item last';
            html += '<p>当前楼为当前页的最后一个item</p>';
        }

        item.innerHTML = html;
        div.appendChild(item);
    }
    document.querySelector('.container').appendChild(div);
}

// 防抖和节流
function throttle(fn, delay, atleast) {
	let timer = null;
	let rAFtimer = null;
	let previous = 0;

	return function() {
		let now = Date.now();
		if (now - previous > atleast) {
			fn();
			previous = now;
		} else {
			if (delay>20) {
				clearTimeout(timer);
				timer = setTimeout(function() {
					fn();
					previous = 0;
				}, delay);
			} else {
				cancelAnimationFrame(rAFtimer);
				rAFtimer = requestAnimationFrame(function() {
					requestIdleCallback(fn);
				});
			}
		}
	}
}

let start = 0; // 开始位置
let count = 20; // 每页展示的数据
createDom(start, count);

// 滚动处理函数
function handleScroller() {
    const maxScrollTop = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight) - window.innerHeight;
    const currentScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);

    if (maxScrollTop - currentScrollTop < 200) {
        start += count;
        createDom(start, count);
    }
}

window.addEventListener('scroll', throttle(handleScroller, 16, 500))