var num = document.getElementsByTagName('img').length; var img = document.getElementsByTagName("img"); var n = 0; //存储图片加载到的位置,避免每次都从第一张图片开始遍历 lazyload(); //页面载入完毕加载可是区域内的图片 window.onscroll = lazyload; functionlazyload() { //监听页面滚动事件 var seeHeight = document.documentElement.clientHeight; //可见区域高度 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度 for (var i = n; i < num; i++) { if (img[i].offsetTop < seeHeight + scrollTop) { if (img[i].getAttribute("src") == "") { img[i].src = img[i].getAttribute("data-src"); } n = i + 1; } } }
var num = document.getElementsByTagName('img').length; var img = document.getElementsByTagName("img"); var n = 0; //存储图片加载到的位置,避免每次都从第一张图片开始遍历 lazyload(); //页面载入完毕加载可是区域内的图片 functionlazyload() { //监听页面滚动事件 var seeHeight = document.documentElement.clientHeight; //可见区域高度 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; //滚动条距离顶部高度 for (var i = n; i < num; i++) { if (img[i].offsetTop < seeHeight + scrollTop) { if (img[i].getAttribute("src") == "") { img[i].src = img[i].getAttribute("data-src"); } n = i + 1; } } } --------------------------------- 以上代码不在重复 -------------------------------- var throttle = function(fun,delay){ var perv = Date.now(); returnfunction(){ var context = this; var now = Date.now(); if (now-perv >= delay){ fun.apply(context,arguments) prev = Date.now(); } } } window.addEventListener('scroll',throttle(lazyload,1000))
定时器方案
1 2 3 4 5 6 7 8 9 10 11 12 13
var throttle = function(fun,delay){ var timer = null; returnfunction(){ var context = this; if(!timer){ timer = setTimeout(function(){ fun.apply(context,arguments) timer = null },delay) } } } window.addEventListener('scroll',throttle(lazyload,1000))
时间戳+定时器方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var throttle = function(fun,delay){ var timer = null; var startTime = Date.now(); returnfunction() { var curTime = Date.now(); var remaining = delay - (curTime - startTime); var context = this; var args = arguments; clearTimeout(timer); if (remaining <= 0) { fun.apply(context, args); startTime = Date.now(); } else { timer = setTimeout(fun, remaining); } } } window.addEventListener('scroll',throttle(lazyload,1000))