美文网首页JavaScriptWeb前端之路让前端飞
函数节流(throttle)与懒加载(lazyload)

函数节流(throttle)与懒加载(lazyload)

作者: 猫仔哦 | 来源:发表于2017-03-14 16:26 被阅读62次

与函数去抖类似,函数节流是也是为了防止过多的DOM操作导致浏览器崩溃问题。但其思想与函数去抖不同,可以拿咖啡机打比方:如果长时间(atleast)未使用它,只要按下按钮就会开始工作,这时再次按下,咖啡机仍然按第一次按下时所需的工作工作,直到第一杯咖啡盛满的时间(delay)结束工作。

函数节流实现具体代码

function throttle(fn, delay, atleast/*, context*/) {
 var timeId = null;
 var startTime = new Date();
 context && (fn = fn.bind(context));

 return function() {
   clearTimeout(timeId);
   var curTime = new Date();

   if(curTime - startTime >= atleast) {
     // 如果再次触发时间足够,则按下按钮立即出咖啡
     fn();
     startTime = curTime;
   } else {
     // 如果时间不足,则等待一段时间再触发
     timeId = setTimeout(fn, delay);
   }
 };
}

懒加载与函数节流的关系

由于懒加载是在onscroll事件触发的基础上进行的,所以函数节流在懒加载中很有必要。

懒加载的实现

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>lazyload</title>
  <style type="text/css">
    /*给图片写入高宽防止加载图片时布局被破坏*/
    img {
      width: 200px;
      height: 200px;
      margin: 10px;
    }
  </style>
</head>
<body>
  ![](./images/loading.png)
  ![](./images/loading.png)
  ![](./images/loading.png)
  ![](./images/loading.png)
  ![](./images/loading.png)
  ![](./images/loading.png)
  ![](./images/loading.png)
  ![](./images/loading.png)
  ![](./images/loading.png)
  ![](./images/loading.png)
  <script type="text/javascript" src="lazyload.js"></script>
  <script type="text/javascript" src="throttle.js"></script>
  <script>
    var images = document.getElementsByTagName('img');
    var loadImages = lazyload(images);
    window.addEventListener('scroll', throttle(loadImages, 500, 1000));
  </script>
</body>
</html>

lazyload.js

function lazyload(images) {
  var n = 0;

  return function() {
    var seeHeight = document.documentElement.clientHieght;
    var scrollHeight = document.documentElement.scrollTop;
    
    [].slice.call(images, n).forEach(function(image) {
      if(image.offsetTop <= seeHeight+scrollHeight && image.src==='./images/laoding.png') {
        image.src = image.dataset.src;
        n++;
      }
    });
  };
}

相关文章

网友评论

    本文标题:函数节流(throttle)与懒加载(lazyload)

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