这个是之前学习写的,最近正好要用到懒加载,如今简单的复习复习。php
记得没错的话是学习了这篇文章后css
https://www.jianshu.com/p/cea62b6868cenode
来看看这个demo长什么样git
先来分析一波,看图片github
HTML代码就不贴出来了,直接看js代码,后面有地址能够下载。ajax
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)//开始加载
} });
//是否可见
lazyLoad.isVisible=function($element){ var winHight = $(window).height(),//屏幕高度
distanceTop = $element.offset().top;//可见块与距离顶部
//判断元素是否进入视野
if(distanceTop <= winHight){ console.log("开始加载"); return true }else{ return false } }
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; };
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++; }); };
lazyLoad.addNode=function(dataitems){ var cardnode = '须要拼接的内容'; return $(cardnode); };
lazyLoad.init($('#visible-block'));
附GitHub地址json
https://github.com/steffenx/H5Lazyloadapp