IntersecionObserver实现无限滚动加载

回到文章
<div class="container"></div>
<div class="observer"></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)
    });
}
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);
}

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

// 处理函数
function handleObserver() {
    start += count;
    createDom(start, count);
}

if (window.IntersectionObserver) {
	var io = new IntersectionObserver(function(entries) {
		var entry = entries[0];
	
		if (entry.intersectionRatio<=0 || !entry.isIntersecting) {
			return false;
		}
		handleObserver();
	}, {
		rootMargin: '400px 0px'
	});
	io.observe(document.querySelector('.observer'));
} else {
	document.querySelector('.container').innerHTML = '<p style="color: #f00; text-align: center; font-size: 18px;">当前环境不支持IntersecionObserver</p>';
}