// 防抖 let lazy_timer; window.addEventListener(‘scroll‘, function () { if (lazy_timer !== null){ clearTimeout(lazy_timer) } lazy_timer = setTimeout(function () { load_lazy(); }, 100) }); // 必须在window.onload里主动调用一次 load_lazy(); // 懒加载 function load_lazy() { $(‘.lazy-img:not([data-l])‘).each(function () { let y = this.getBoundingClientRect().top; if ((y+this.offsetHeight >= 0 && y <= document.body.clientHeight) || this.getAttribute(‘data-main‘) === ‘t‘) { this.src = this.getAttribute(‘data-s‘); this.setAttribute(‘data-l‘, ‘‘); } }); }
以上代码很简洁,主要就是三点
原文:https://www.cnblogs.com/yunyuyuan/p/12432777.html