Probably a simple implementation of lazy loading

This is written in the previous study, recently just to use lazy loading, and now a simple review review.

After remember correctly is learning this article

https://www.jianshu.com/p/cea62b6868ce

Take a look at this demo look like

First to analyze the wave, see pictures

HTML code is not posted, and direct look js code, followed by the address can be downloaded.

1. listening slip events

   var lazyLoad={};
    var isblock = true;//初始可见块为可见
    var timer=1;//加载计数
    var $block;//可见块

    window.lazyLoad=lazyLoad;//暴露对象
    //监听滑动
    $("body").on('scroll',function(){
        //如果不可见
        if(!isblock){
            return
        }
        //判断可见块是否可见
        if(lazyLoad.isVisible($block)){  
            lazyLoad.init($block)//开始加载
        }
    });

2.判断目标块是否进入人们视野

  //是否可见
    lazyLoad.isVisible=function($element){
        var winHight = $(window).height(),//屏幕高度
            distanceTop = $element.offset().top;//可见块与距离顶部
        //判断元素是否进入视野
        if(distanceTop <= winHight){  
            console.log("开始加载");
            return true
        }else{
            return false
        }
    }

3.开始加载

    lazyLoad.init=function(input){
        $block=input;

        //获取数据
        lazyLoad.getdata(function(datalist){
            isblock=true;
            //遍历数据
            $.each(datalist,function(index,history){
                // 拿到的数据进行拼接
                var $node = lazyLoad.addNode(history)   
                $('.history-container').append($node)
            });
        });
        $block.css("visibility","visible");
        isblock=false;
    };

4.ajax请求

    lazyLoad.getdata=function(callback){
        $.ajax({
                url:"http://yyyxuan.cn/lay-eggs/js/test.php",
                type: "POST",
                data:"time="+timer
                }).done(function(ret){
                        //转化json
                        var json=$.parseJSON(ret);
                        if (json==null) {
                            $block.css("visibility","visible");
                            $block.text("到底了");
                            return;
                        }
                        else{$block.css("visibility","hidden");}
                        callback(json.data);
                        timer++;
                    });
    };

 5.元素拼接

lazyLoad.addNode=function(dataitems){
        var cardnode = '需要拼接的内容';
        return $(cardnode);
    };

6.在页面调用init(),并传入这个目标块

lazyLoad.init($('#visible-block'));

附GitHub地址

https://github.com/steffenx/H5Lazyload

Guess you like

Origin www.cnblogs.com/Steffen-xuan/p/11199824.html