博客列表 >JS懒加载

JS懒加载

遇上你是我的缘的博客
遇上你是我的缘的博客原创
2019年07月16日 17:24:30769浏览
<script>
    var container=document.createElement('div');
    var frag=document.createDocumentFragment();

    for(var i=1 ;i<13;i++){
        var imgUrl='images/'+i+'.jpg';
        var img=document.createElement('img');
        img.setAttribute('data-index',imgUrl);
        img.setAttribute('src','images/loading.gif');
        img.setAttribute('style','width:600px;height:350px;margin: 5px;');
        frag.appendChild(img);
        // console.log(img)
    }
    container.appendChild(frag);
    document.body.insertBefore(container,document.body.firstElementChild)
    //——————————————————————————————————————————以上动态生成占位图片——
    window.addEventListener('scroll',lazyLoaded);
    function lazyLoaded(){
        //滚动条高度
        var scrollTop= document.documentElement.scrollTop;
        //可视区高度
        var clientHeight=document.documentElement.clientHeight;

        var imgArr=Array.prototype.slice.call(document.images);
        imgArr.forEach(function(ev){
           console.log('滚动条高度:'+scrollTop+' 可视区高度:'+clientHeight);

          if(ev.offsetTop<=(scrollTop+clientHeight)){
              ev.src=ev.dataset.index;
          }
       })


    }

    window.addEventListener('load',lazyLoaded);

</script>


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议