Skip to content

滚动加载

1. 方式,使用requestAmnimationFrame

js

function lazyLoad(callback) {
    let ticking = false;

    function onScroll() {
        if (!ticking) {
            window.requestAnimationFrame(() => {
                const scrollTop = document.documentElement.offsetTop // 滚动条举例顶部高度
                const clientHeight = document.documentElement.clientHeight // 可视区域高度
                const scrollHeight = document.documentElement.scrollHeight // 总高度
                
                if (scrollTop + clientHeight >= scrollHeight - 100) {
                    // 触发懒加载
                    callback();
                }
                ticking = false;
            });
            ticking = true;
        }
    }

    window.addEventListener('scroll', onScroll);
}

2. 使用IntersectionObserver

用于监听目标元素与视口或其他元素的交叉状态(即元素是否进入可视区域)

js

function lazyScrollLoad () {
    
    const handleObserver = (entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                // 触发懒加载
                console.log('元素进入可视区域,执行懒加载');
                // 可以在这里调用加载函数
                observer.unobserve(entry.target); // 停止观察
            }
        });
    }
    
    const observer = new InsectionObserver(handleObserver)
    
    observer.observe(document.querySelector('.lazy-load-element'));
}