废话就很少说了,直接上教程吧html
将须要作懒加载的元素占一下位,这里为何我是用一个类名是来获取元素下面会有介绍app
<img class="J_lazyload" data-src="{{路径}}" />
<!-- 这里是给背景作懒加载 -->
<div class="J_lazyload" data-src="{{路径}}"></div>
复制代码
定义一个lazyload的构造函数,而且定义一个获取对应的节点位置的方法dom
function LazyLoad() {
this.getPositions()
this.initData()
}
LazyLoad.prototype.getPositions = function () {
//这里须要使用获取静态节点列表,不能获取动态节点列表,由于须要移除J_lazyload钩子
let imgs = document.querySelectorAll('.J_lazyload')
let targetHeight = window.innerHeight
for (let i = 0, ii = imgs.length; i < ii; i++) {
let items = imgs[i]
let handle = ((img)=>{
return function(){
if (img.tagName.toLowerCase() === 'img') {
img.src = img.dataset.src;
} else {
img.style['background-image'] = 'url(' + img.dataset.src + ')';
}
}
})(items)
let pos = items.getBoundingClientRect()
// 这里是判断是否在屏幕内
if (pos.top < targetHeight && pos.bottom > 0) {
// 这里是使用的Image,下载完成后再将对应的dom节点的src
let image = new Image()
image.src = items.dataset.src
image.onload = handle
// 移除J_lazyload钩子,防止重复进行懒加载
items.classList.remove('J_lazyload')
}
}
}
复制代码
绑定事件以前 = >,先来讲一下防抖,因为频繁触发,因此这里须要引入防抖函数函数
function debounce(fn, time) {
var timer = null;
time = time || 60;
var _arguments;
return function () {
var self = this
clearTimeout(timer)
_arguments = [...arguments];
timer = setTimeout(() => {
fn.apply(self, _arguments)
timer = null
}, time)
}
}
复制代码
LazyLoad.prototype.initData = function () {
let scrolls = debounce(this.replaceUrl, 1000).bind(this)
window.addEventListener('scroll', scrolls)
}
// 进行懒加载
LazyLoad.prototype.replaceUrl = function () {
this.getPositions()
}
复制代码
以上就是实现一个基本的懒加载了。以为不错的话,能够点个赞呀ui