实现步骤
1、获取容器元素的高度 clientHeight
2、获取列表项元素的高度 offsetHeight
3、计算可视区域应该渲染的列表项的个数 count = clientHeight / offsetHeight
4、计算可视区域数据渲染的起始位置 start
5、计算可视区域数据渲染的结束位置 end
6、对完整长列表数据进行截断 sliceList = dataList.slice(start, end)
7、渲染截断后的列表数据,进而实现无限加载
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
}
html,body,.wrapper{
height: 100%;
}
ul,li{
list-style: none;
height: 40px;
line-height: 40px;
}
.top{
position: fixed;
top:0;
width: 100%;
background-color: #fff;
height: 40px;
padding:10px;
font-size: 16px;
}
.container{
margin-left:10px;
}
</style>
</head>
<body>
<div class="wrapper">
<p class="top"></p>
<div style="height: 60px;"></div>
<ul class="container">
<a class="sentinels">...</a>
</ul>
</div>
<script src="js/loadLotOfData.js"></script>
</body>
</html>
//loadLotOfData.js
//创建10万条数据
function getDataList(){
var data = []
for(var i = 0;i<100000;i++){
data.push({index:i,value:i+10})
}
return data
}
//获取dom
function $(selector){
return document.querySelecter(selector)
}
//加载数据
function loadData(start,end){
let sliceData = getDataList().slice(start, end)
let fragment = document.createDocumentFragment();
for(let i = 0; i < sliceData.length; i++) {
let li = document.createElement('li');
li.innerText = JSON.stringify(sliceData[i])]
fragment.appendChild(li);
}
$('.container').insertBefore(fragment, $('.sentinels'));
}
//
function intersection(){
var count = Math.ceil(document.body.clientHeight/40)
var startIndex = 0;
var endIndex = 0
let io = new IntersectionObserver(function(entries) {
loadData(startIndex ,count)
if(entries[0].isIntersecting){
startIndex = startIndex += count
endIndex = startIndex + count
if(endIndex>=getDataList().length){
io.unobserve(entries[0].target)
}
}
requestAnimationFrame(() => {
loadData(startIndex, endIndex)
let num = Number(getDataList().length - startIndex)
let info =` 还有${num}条数据`
$('.top').innerText = info
})
})
io.observe($('.sentinels'));
})
intersection()
github地址:https://github.com/yanlitingjy/loadData