Native lazy loading -js

window.onload = function(){

        var scrollTop = window.scrollY;
        var imgs = Array.from(document.querySelectorAll('img'));
        lazyLoad();
        // 采用了节流函数
        window.addEventListener('scroll',throttle(lazyLoad,500,1000));

        function throttle(fun, delay, time) {
            var timeout,
                startTime = new Date();
            return function() {

                var context = this,
                    args = arguments,
                    curTime= New new a Date (); 
                the clearTimeout (timeout); 
                // if the trigger reaches a predetermined time interval, triggers Handler 
                the console.log (curTime - the startTime)
                 IF (curTime - the startTime> = Time) { 
                    Fun (); 
                    the startTime = curTime;
                     // did not reach the trigger interval, to reset the timer 
                } the else { 
                    timeout = the setTimeout (Fun, Delay); 
                } 
            }; 
        }; 
        // actually want to bind on the scroll event Handler 
        // need access to imgs, scroll
        function lazyLoad(){
            scrollTop = window.scrollY;
            imgs.forEach((item,index)=>{
                if( scrollTop===0 && item.dataset.src !== '' && item.offsetTop < window.innerHeight + scrollTop ){
                    // alert()
                    item.setAttribute('src',item.dataset.src)
                    item.setAttribute('data-src','')
                }else if( item.dataset.src !== '' && item.offsetTop < window.innerHeight + scrollTop && item.offsetTop > scrollTop ){
                    item.setAttribute('src',item.dataset.src)
                    item.setAttribute('data-src','')
                }
            })
        }

    }

 

 

Guess you like

Origin www.cnblogs.com/xuziwen/p/12177792.html