自我介绍:大家好,我是吉帅振的网络日志;微信公众号:吉帅振的网络日志;前端开发工程师,工作4年,去过上海、北京,经历创业公司,进过大厂,现在郑州敲代码。
一、前言
在开发过程中,如果遇到某一场景:每组数据都要先通过很庞大的计算,然后把计算的结果 Render 到页面上。一般情况,就会需要等待一段有感的时间,才能看到结果出现在画面上。为了解决这差劲用户体验,就使用到的标题上说到的 Lazy Loading 来处理。简单说就是,如果显示的数据有10条,但因为一个页面大概只能呈现2-3条,那我就先计算那 2-3条数据显示就好,剩下的数据等使用者需要再继续显示,这样等待时间就不会太久。
二、案例
三、代码
const data = Array.from(Array(200)).map(
(_value, index) => `第 ${index + 1} 筆資料`
);
const render = () => {
const list = document.querySelector('.list');
const LOAD_DATA_COUNT = 50;
const startLoadIndex = list.childNodes.length;
const endLoadIndex = startLoadIndex + LOAD_DATA_COUNT;
for (let i = startLoadIndex; i < endLoadIndex; i++) {
if (data[i]) {
const text = document.createTextNode(data[i]);
const li = document.createElement('li');
li.appendChild(text);
list.appendChild(li);
}
}
if (endLoadIndex >= data.length) {
const loading = document.querySelector('.loading');
loading.style.display = 'none';
intersectionObserver.unobserve(loading);
}
};
render();
const intersectionObserver = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) {
setTimeout(render, 1000);
}
}
);
intersectionObserver.observe(
document.querySelector('.loading')
);
1.先用循环产生 200 笔的假数据。
2.写一个 render 的方法,把还没载入的数据循环加去,这里一次加 50 笔数据。
3.在 render 内加完数据,去判断当前加到的 index 有没有大于数据总数,如果有的话代表所有数据显示完了,因此隐藏 loading,并移除 Intersection Observer API 对 loading 的监听。
4.毕竟一开始画面上还是要有数据,所以先手动执行第一次 render 方法。
5.用 Intersection Observer API 监听 loading,只要一出现在画面上,代表使用者看完目前的数据,就要在执行 render。这里为了有真正 render 的感觉,用 setTimeout 来延迟 1 秒。
四、总结
最后来看一下支持情况。ntersection Observe API 的支持度算不错了,但如果产品有要考虑到 IE 的客户群就没办法用了。
我正在参加「创意开发 投稿大赛」详情请看:掘金创意开发大赛来了!