懶加載

一、如何判斷一個(gè)元素是否出現(xiàn)在窗口可視范圍(瀏覽器的上邊緣和下邊緣之間,肉眼可視)。寫一個(gè)函數(shù) isVisible實(shí)現(xiàn)。

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;
    }
}

二、當(dāng)窗口滾動(dòng)時(shí),判斷一個(gè)元素是不是出現(xiàn)在窗口可視范圍。每次出現(xiàn)都在控制臺(tái)打印 true 。用代碼實(shí)現(xiàn)。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>元素每次出現(xiàn)都在控制臺(tái)打印</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">我出現(xiàn)在可視窗口</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>

預(yù)覽

三、當(dāng)窗口滾動(dòng)時(shí),判斷一個(gè)元素是不是出現(xiàn)在窗口可視范圍。在元素第一次出現(xiàn)時(shí)在控制臺(tái)打印 true,以后再次出現(xiàn)不做任何處理。用代碼實(shí)現(xiàn)。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>元素每次出現(xiàn)都在控制臺(tái)打印</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">我出現(xiàn)在可視窗口</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>

預(yù)覽

四、圖片懶加載的原理是什么?

當(dāng)訪問(wèn)一個(gè)頁(yè)面的時(shí)候,首先把img的src置為正在加載的圖片地址,因?yàn)樗械倪@個(gè)背景圖片都一樣,所以只需加載一次。真正的所需加載的地址放到另外的屬性上面。等到頁(yè)面滾動(dòng)到那一部分的時(shí)候,再把頁(yè)面中的img標(biāo)簽的src屬性發(fā)送請(qǐng)求并下載圖片,通過(guò)動(dòng)態(tài)改變img的src屬性實(shí)現(xiàn)。減少網(wǎng)絡(luò)請(qǐng)求。

五、實(shí)現(xiàn)視頻中的圖片懶加載效果。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>簡(jiǎn)單的圖片懶加載</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="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
      <li><a href="#">![](http://upload-images.jianshu.io/upload_images/2244513-f99ff2db555e14d2.gif?imageMogr2/auto-orient/strip)</a></li>
    </ul>
  </div>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script>
  // 先調(diào)用一次,省得要鼠標(biāo)滾動(dòng)才加載
    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>

預(yù)覽

六、實(shí)現(xiàn)視頻中的新聞懶加載效果。

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>
    <!-- 頁(yè)面一開始沒(méi)有滾動(dòng)條,利用p出現(xiàn)發(fā)請(qǐng)求。 -->
  </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("獲取新聞出錯(cuò)!");
        }
      }).fail(function() {
        alert("系統(tǒng)異常!");
      })
    }

    function appendHtml(news) {
      if(news.length == 0) {
        isOver = true;
        $('.wrap').append('<p>沒(méi)有更多新聞啦~~~</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: '中國(guó)轟6K研發(fā)險(xiǎn)些被俄羅斯發(fā)動(dòng)機(jī)廠商卡脖子',
            brif:  '近日,轟6K"戰(zhàn)神"轟炸機(jī)首次公開亮相。在中國(guó)...'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '外媒稱中國(guó)已經(jīng)決心造出世界先進(jìn)的航空發(fā)動(dòng)機(jī)',
            brif: '資料圖:2012年11月14日,第九屆中國(guó)國(guó)際...'
        },
        {
            link: 'http://view.inews.qq.com/a/20160828A007LB00',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531727868_150120/0',
            title: '傳奇導(dǎo)彈專家馮·布勞恩:其實(shí)到美國(guó)后曾被當(dāng)局忽視',
            brif: '小火箭出品本文作者:邢強(qiáng)博士原文標(biāo)題:布勞恩博...'
        },
        {
            link: 'http://xw.qq.com/mil/20160830033420/MIL2016083003342001',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531646423_150120/0',
            title: '中國(guó)空軍演習(xí)加快反導(dǎo)能力建設(shè) 韓媒:或針對(duì)“薩德',
            brif: '中國(guó)空軍演習(xí)加快反導(dǎo)能力建設(shè) 韓媒:或針對(duì)“薩德'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '外媒稱中國(guó)已經(jīng)決心造出世界先進(jìn)的航空發(fā)動(dòng)機(jī)',
            brif: '資料圖:2012年11月14日,第九屆中國(guó)國(guó)際...'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '為了喝酒,應(yīng)該海軍當(dāng)年那些水兵也是蠻拼的……',
            brif: '囂張(aggressive)這個(gè)詞,腐國(guó)海軍當(dāng)...'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '西媒臆斷老撾“棄華投美” 認(rèn)為現(xiàn)政府更親越南',
            brif: '西媒臆斷老撾“棄華投美” 認(rèn)為現(xiàn)政府更親越南'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '中國(guó)武警2016年征兵宣傳片震撼首發(fā)',
            brif: '中國(guó)武警2016年征兵宣傳片震撼首發(fā)'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '韓國(guó)多次宣稱“一旦開戰(zhàn)三天內(nèi)消滅朝鮮空軍”,靠譜嗎?',
            brif: '韓國(guó)多次宣稱“一旦開戰(zhàn)三天內(nèi)消滅朝鮮空軍”,靠譜嗎?'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '韓促朝停止詆毀韓國(guó)元首 批其喪失最基本禮儀常識(shí)',
            brif: '韓促朝停止詆毀韓國(guó)元首 批其喪失最基本禮儀常識(shí)'
        },
        {
            link: 'http://xw.qq.com/mil/20160830033420/MIL2016083003342001',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531646423_150120/0',
            title: '中國(guó)空軍演習(xí)加快反導(dǎo)能力建設(shè) 韓媒:或針對(duì)“薩德',
            brif: '中國(guó)空軍演習(xí)加快反導(dǎo)能力建設(shè) 韓媒:或針對(duì)“薩德'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '外媒稱中國(guó)已經(jīng)決心造出世界先進(jìn)的航空發(fā)動(dòng)機(jī)',
            brif: '資料圖:2012年11月14日,第九屆中國(guó)國(guó)際...'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '為了喝酒,應(yīng)該海軍當(dāng)年那些水兵也是蠻拼的……',
            brif: '囂張(aggressive)這個(gè)詞,腐國(guó)海軍當(dāng)...'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '西媒臆斷老撾“棄華投美” 認(rèn)為現(xiàn)政府更親越南',
            brif: '西媒臆斷老撾“棄華投美” 認(rèn)為現(xiàn)政府更親越南'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '中國(guó)武警2016年征兵宣傳片震撼首發(fā)',
            brif: '中國(guó)武警2016年征兵宣傳片震撼首發(fā)'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '韓國(guó)多次宣稱“一旦開戰(zhàn)三天內(nèi)消滅朝鮮空軍”,靠譜嗎?',
            brif: '韓國(guó)多次宣稱“一旦開戰(zhàn)三天內(nèi)消滅朝鮮空軍”,靠譜嗎?'
        },
        {
            link: 'http://xw.qq.com/mil/20160830028700/MIL2016083002870002',
            img: 'http://inews.gtimg.com/newsapp_ls/0/531644649_150120/0',
            title: '韓促朝停止詆毀韓國(guó)元首 批其喪失最基本禮儀常識(shí)',
            brif: '韓促朝停止詆毀韓國(guó)元首 批其喪失最基本禮儀常識(shí)'
        }
    ];
    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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容