使用原生实现懒加载
实现原理
- 先把所有的图片都不显示出来
- 把地址放到自定义属性上保存起来
- 获取一些值(窗口文档图片)
参考地址
<script>
const div = document.querySelector('div')
getList()
function getList() {
const xhr = new XMLHttpRequest
xhr.open('get', '/list')
xhr.onload = function () {
console.log(xhr.responseText)
// 拿到响应的数据,传入到回调函数
bindHtml(JSON.parse(xhr.responseText))
}
xhr.send()
}
function bindHtml(list) {
// 拿到数据,遍历数组中的每一项
list.forEach(item => {
// console.log(item)
// 创建一个图片对象
const img = new Image
img.dataset.src = item.goods_big_logo
div.appendChild(img)
})
lazyLoad()
window.onscroll = function () {
lazyLoad()
}
}
function lazyLoad() {
const imgs = document.querySelectorAll('img')
// 窗口的高度
const windowHeight = document.documentElement.clientHeight
// 浏览器卷曲的高度
const scrollY = window.scrollY
imgs.forEach(item => {
if (item.offsetTop - scrollY < windowHeight + 200) {
// 我到了可是区域里面了
item.src = item.dataset.src
}
})
}
</script>
使用lazyload.js插件来写
<div></div>
<script src="https://cdn.jsdelivr.net/npm/lazyload@2.0.0-rc.2/lazyload.js"></script>
<script>
const div = document.querySelector('div')
getList()
function getList() {
const xhr = new XMLHttpRequest
xhr.open('get', '/list')
xhr.onload = function () {
bindHtml(JSON.parse(xhr.responseText))
}
xhr.send()
}
function bindHtml(list) {
list.forEach(item => {
const img = new Image
img.src = '/public/test.gif'
img.dataset.src = item.goods_big_logo
img.className = 'lazyload'
div.appendChild(img)
})
lazyload()
}
</script>