需求描述
日常开发中, 遇到元素特别多的页面, 例如全是图表的页面,如果图表过多,造成页面卡顿。
若只显示在屏幕可视范围内的图
,范围外的销毁
,可大大提高页面性能。
具体实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| function isOnScreen(element) { let on_screen_height = 20;
let rect = element.getBoundingClientRect(); let windowHeight = window.innerHeight || document.documentElement.clientHeight;
let elementHeight = element.offsetHeight;
let onScreenHeight = on_screen_height > elementHeight ? elementHeight : on_screen_height;
let elementBottomToWindowTop = rect.top + elementHeight; let bottomBoundingOnScreen = elementBottomToWindowTop >= onScreenHeight;
let elementTopToWindowBottom = windowHeight - (rect.bottom - elementHeight); let topBoundingOnScreen = elementTopToWindowBottom >= onScreenHeight;
return bottomBoundingOnScreen && topBoundingOnScreen; }
for (let i=0; i<=6; i++) { let element = document.getElementById(i); console.log(isOnScreen(element)) if (isOnScreen(element)) { if () { } } else { } }
|
1 2 3 4 5 6 7 8 9 10
| <ul> <li id="0"></li> <li id="1"></li> <li id="2"></li> <li id="3"></li> <li id="4"></li> <li id="5"></li> <li id="6"></li> ... </ul>
|
滚动结束事件
由于原生 JavaScript 没有对应滑动结束事件,需要采取定时模拟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| let element = document.getElementById('id');
element.onscroll = () => { if (window.scrollTimer) { clearTimeout(window.scrollTimer) clearTimeout(window.scrollTimer._id) } window.scrollTimer = setTimeout(callback, 300) }
function callback() { }
element.scrollTo({ left: 0, top: num, behavior: 'smooth' })
|