懒加载

作者: 婷楼沐熙 | 来源:发表于2017-02-16 20:09 被阅读50次

一、如何判断一个元素是否出现在窗口可视范围(浏览器的上边缘和下边缘之间,肉眼可视)。写一个函数 isVisible实现。

function isVisible($node) {
    var windowHeight = $(window).height(),
          scrollTop = $(window).scrollTop(),
          offsetTop = $node.offset().top,
          nodeHeight = $node.outerHeight(true);
    if (windowHeight + scrollTop > offsetTop && scrollTop < offsetTop + nodeHeight) {
        return true;
    }else{
        return false;
    }
}

二、当窗口滚动时,判断一个元素是不是出现在窗口可视范围。每次出现都在控制台打印 true 。用代码实现。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>元素每次出现都在控制台打印</title>
  <style>
    div:nth-child(2n+1) {
      background: pink;
      width: 500px;
      height: 500px;
    }
    div:nth-child(2n) {
      background: yellow;
      width: 500px;
      height: 500px;
    }
  </style>
</head>
<body>
  <div>
    <div>1</div>
    <div>2</div>
    <div class="visible">我出现在可视窗口</div>
    <div>4</div>
  </div>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script>
    var $visible = $('.visible');
    $(window).on('scroll', function() {
      if(isVisible($visible)) {
        console.log('true');
      }
    })
    function isVisible($node) {
      var windowHeight = $(window).height(),
          scrollTop = $(window).scrollTop(),
          offsetTop = $node.offset().top,
          nodeHeight = $node.outerHeight(true);
      if (windowHeight + scrollTop > offsetTop && scrollTop < offsetTop + nodeHeight) {
        return true;
      }else{
        return false;
      }
    }
  </script>
</body>
</html>

预览

三、当窗口滚动时,判断一个元素是不是出现在窗口可视范围。在元素第一次出现时在控制台打印 true,以后再次出现不做任何处理。用代码实现。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>元素每次出现都在控制台打印</title>
  <style>
    div:nth-child(2n+1) {
      background: pink;
      width: 500px;
      height: 500px;
    }
    div:nth-child(2n) {
      background: yellow;
      width: 500px;
      height: 500px;
    }
  </style>
</head>
<body>
  <div>
    <div>1</div>
    <div>2</div>
    <div class="visible">我出现在可视窗口</div>
    <div>4</div>
  </div>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script>
    var $visible = $('.visible');
    var flag = true;
    $(window).on('scroll', function() {
      if(flag) {
        isVisible($visible);
      }
    })

    function isVisible($node) {
      var windowHeight = $(window).height(),
            scrollTop = $(window).scrollTop(),
            offsetTop = $node.offset().top,
            nodeHeight = $node.outerHeight(true);
      if (windowHeight + scrollTop > offsetTop && scrollTop < offsetTop + nodeHeight) {
        console.log('true');
        flag = false;
        return true;
      }else{
        return false;
      }
    }
  </script>
</body>
</html>

预览

四、图片懒加载的原理是什么?

当访问一个页面的时候,首先把img的src置为正在加载的图片地址,因为所有的这个背景图片都一样,所以只需加载一次。真正的所需加载的地址放到另外的属性上面。等到页面滚动到那一部分的时候,再把页面中的img标签的src属性发送请求并下载图片,通过动态改变img的src属性实现。减少网络请求。

五、实现视频中的图片懒加载效果。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>简单的图片懒加载</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    li{
      list-style: none;
    }
    .wrap{
      width: 960px;
      margin: 20px auto;
      background: rgb(24,20,37);
    }
    .inner{
      margin-left: -30px;
      padding-top: 30px;
    }
    .clearfix:after{
      content: '';
      display: block;
      clear: both;
    }
    .inner li{
      float: left;
      margin-left: 30px;
      text-align: center;
      margin-bottom: 30px;
    }
    img{
      width: 465px;
        height: 305px;
    }
  </style>
</head>
<body>
  <div class="wrap">
    <ul class="inner clearfix">
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](https://img.haomeiwen.com/i2244513/f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
    </ul>
  </div>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script>
  // 先调用一次,省得要鼠标滚动才加载
    check();
    $(window).on('scroll', check);
    if($('.inner img').not('.load')) {
      $('.wrap').append('<p>图片加载完啦~~~</p>');
      $('p').css('color', '#fff');
    }
    function check() {
      $('.inner img').not('.load').each(function() {
        if(isVisible($(this))) {
          showImage($(this));
        }
      })
    }

    function isVisible($node) {
      var windowHeight = $(window).height(),
            scrollTop = $(window).scrollTop(),
            offsetTop = $node.offset().top,
            nodeHeight = $node.outerHeight(true);
      if (windowHeight + scrollTop > offsetTop && scrollTop < offsetTop + nodeHeight) {
          return true;
      }else{
          return false;
      }
    }

    function showImage($imgs) {
      $imgs.each(function() {
        var imgURL = $(this).attr('data-src');
        $(this).attr('src', imgURL);
        $(this).addClass('load');
      })
    }
  </script>
</body>
</html>

预览

六、实现视频中的新闻懒加载效果。

newsGetMore.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>新闻懒加载</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    a{
     color: #333;
     text-decoration: none;
   }
   li{
     list-style: none;
   }
   .clearfix:after {
            content: '';
            display: block;
            clear: both;
        }
   .wrap{
     max-width: 600px;
     margin: 0 auto;
   }
   .item{
     margin-top: 20px;
   }
   .item:after{
     content: '';
     display: block;
     clear: both;
   }
   .item .thumb img{
     width: 50px;
     height: 50px;
   }
   .item .thumb {
     float: left;
   }
   .item h2{
     margin-left: 60px;
     font-size: 14px;

   }
   .item p{
     margin-left: 60px;
     font-size: 14px;
     margin-top: 10px;
     color: #ccc;
   }
   .load-more{
     visibility: hidden;
     margin: 3px;
     height: 3px;
   }
  </style>
</head>
<body>
  <div class="wrap">
    <ul class="news">

    </ul>
    <p class="load-more"></p>
    <!-- 页面一开始没有滚动条,利用p出现发请求。 -->
  </div>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script>
    var pageNumber = 0,
        isLoaded = true,
        isOver = false;
    getNews();
    $(window).on('scroll', checkNews);

    function getNews() {
      isLoaded = false;
      $.get('/getNews', {page: pageNumber}).done(function(res) {
        isLoaded = true;
        if(res.status == 0) {
          pageNumber++;
          appendHtml(res.filterNews);
          checkNews();
        }else{
          alert("获取新闻出错!");
        }
      }).fail(function() {
        alert("系统异常!");
      })
    }

    function appendHtml(news) {
      if(news.length == 0) {
        isOver = true;
        $('.wrap').append('<p>没有更多新闻啦~~~</p>')
      }
      var htmls = '';
      $.each(news, function(){
        console.log(this.img);
        htmls += '<li class="item clearfix">';
        htmls += '<a href="' + this.link + '">';
        htmls += '<div class="thumb"> ![](' + this.img + ')</div>';
        htmls += '<h2>'+this.title+'</h2>';
        htmls += '<p>'+this.brif+'</p>';
        htmls += '</a></li>';
      })
      console.log(htmls);
      $('.news').append(htmls);
      // $('.news').append(news.map(new => `
      //     <li class="item">
      //       <a href="${new.link}">
      //         ![](${new.img})</div>
      //         <h2>${new.title}</h2>
      //         <p>${new.brief}</p>
      //       </a>
      //     </li>
      // `).join(''))
    }

    function checkNews() {
      if(isShow($('.load-more')) && isLoaded && !isOver) {
        getNews();
      }
    }

    function isShow($node) {
      var windowHeight = $(window).height(),
          scrollTop = $(window).scrollTop(),
          offsetTop = $node.offset().top,
          nodeHeight = $node.outerHeight(true);
      if((scrollTop < offsetTop + nodeHeight) && (windowHeight + scrollTop > offsetTop)) {
        return true;
      }else{
        return false;
      }
    }
  </script>
</body>
</html>

router.js

app.get('/getNews', function(req, res) {
    var news = [
        {
            link: 'http://view.inews.qq.com/a/20160830A02SEB00',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531730377_150120/0',
            title: '中国轰6K研发险些被俄罗斯发动机厂商卡脖子',
            brif:  '近日,轰6K"战神"轰炸机首次公开亮相。在中国...'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '外媒称中国已经决心造出世界先进的航空发动机',
            brif: '资料图:2012年11月14日,第九届中国国际...'
        },
        {
            link: 'http://view.inews.qq.com/a/20160828A007LB00',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531727868_150120/0',
            title: '传奇导弹专家冯·布劳恩:其实到美国后曾被当局忽视',
            brif: '小火箭出品本文作者:邢强博士原文标题:布劳恩博...'
        },
        {
            link: 'http://xw.qq.com/mil/20160830033420/MIL2016083003342001',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531646423_150120/0',
            title: '中国空军演习加快反导能力建设 韩媒:或针对“萨德',
            brif: '中国空军演习加快反导能力建设 韩媒:或针对“萨德'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '外媒称中国已经决心造出世界先进的航空发动机',
            brif: '资料图:2012年11月14日,第九届中国国际...'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '为了喝酒,应该海军当年那些水兵也是蛮拼的……',
            brif: '嚣张(aggressive)这个词,腐国海军当...'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '西媒臆断老挝“弃华投美” 认为现政府更亲越南',
            brif: '西媒臆断老挝“弃华投美” 认为现政府更亲越南'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '中国武警2016年征兵宣传片震撼首发',
            brif: '中国武警2016年征兵宣传片震撼首发'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '韩国多次宣称“一旦开战三天内消灭朝鲜空军”,靠谱吗?',
            brif: '韩国多次宣称“一旦开战三天内消灭朝鲜空军”,靠谱吗?'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '韩促朝停止诋毁韩国元首 批其丧失最基本礼仪常识',
            brif: '韩促朝停止诋毁韩国元首 批其丧失最基本礼仪常识'
        },
        {
            link: 'http://xw.qq.com/mil/20160830033420/MIL2016083003342001',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531646423_150120/0',
            title: '中国空军演习加快反导能力建设 韩媒:或针对“萨德',
            brif: '中国空军演习加快反导能力建设 韩媒:或针对“萨德'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '外媒称中国已经决心造出世界先进的航空发动机',
            brif: '资料图:2012年11月14日,第九届中国国际...'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '为了喝酒,应该海军当年那些水兵也是蛮拼的……',
            brif: '嚣张(aggressive)这个词,腐国海军当...'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '西媒臆断老挝“弃华投美” 认为现政府更亲越南',
            brif: '西媒臆断老挝“弃华投美” 认为现政府更亲越南'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '中国武警2016年征兵宣传片震撼首发',
            brif: '中国武警2016年征兵宣传片震撼首发'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '韩国多次宣称“一旦开战三天内消灭朝鲜空军”,靠谱吗?',
            brif: '韩国多次宣称“一旦开战三天内消灭朝鲜空军”,靠谱吗?'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '韩促朝停止诋毁韩国元首 批其丧失最基本礼仪常识',
            brif: '韩促朝停止诋毁韩国元首 批其丧失最基本礼仪常识'
        }
    ];
    var page = req.query.page;
    var len = 3;
    var filterNews = news.slice(page*len, page*len+len);
    res.send({
        status: 0,
        filterNews
    });
});

Paste_Image.png

相关文章

  • iOS开发,懒加载

    什么是懒加载? 懒加载--比较懒的加载方式,需要的时候才加载,也称为延时加载。 所谓懒加载既是重写get方法,一定...

  • iOS开发UI篇-懒加载、重写setter方法赋值

    一、懒加载 1.懒加载定义 懒加载——也称为延迟加载,即在需要的时候才加载(效率低,占用内存小)。所谓懒加载,写的...

  • Fragment结合ViewPager之懒加载

    什么是懒加载?为什么要用懒加载?### 1、什么是懒加载 懒加载就是当ViewPager和Fragment结合在一...

  • iOS懒加载注意事项

    懒加载 1.懒加载 懒加载——也称为延迟加载,即在需要的时候才加载(效率低,占用内存小)。所谓懒加载,写的是其ge...

  • web优化之懒加载和预加载

    懒加载和预加载是常用的web优化的手段。所以我们首先应该明白什么是懒加载和预加载。懒加载:懒加载也加延迟加载,延迟...

  • fragment 懒加载

    fragment 的懒加载 懒加载 什么是懒加载:只有在 fragment 显示在界面的时候,才进行数据的加载 懒...

  • 懒加载和预加载

    懒加载和预加载 1. 懒加载 1. 什么是懒加载? 懒加载也就是延迟加载 当访问一个页面的时候,先把img元素或是...

  • Android 懒加载优化

    目录介绍 1.什么是懒加载1.1 什么是预加载1.2 懒加载介绍1.3 懒加载概括 2.实际应用中有哪些懒加载案例...

  • Swift语法点

    1 懒加载 懒加载与OC中的懒加载的区别:懒加载的类一旦 设置为nil 后, 懒加载就不会再次执行,与OC中不同,...

  • UICollectionView

    UICollectionViewFlowLayout懒加载 UICollectionView懒加载 注册item ...

网友评论

      本文标题:懒加载

      本文链接:https://www.haomeiwen.com/subject/pgdqwttx.html