图片懒加载实现(JS简单实现)
HTML页面中,所有需要懒加载的图片,首先属性src设置为空,设置另一个属性lazy-data-src用于暂存图片的地址;
当需要加载时,再将属性lazy-data-src的值赋值给src,图片就加载了。
注意:属性名 lazy-data-src 是你可以随意起名字的,只需要在JS里面修改对应就好了。
复制收展HTML<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片懒加载</title>
<style>
#imgList {width: 800px;margin: 0 auto;}
</style>
</head>
<body>
<div id="imgList">
<img src="" lazy-data-src="/img/1.png" onerror="this.src='/imgs/loading/load6.gif';this.onerror=null" >
<img src="" lazy-data-src="/img/2.png" onerror="this.src='/imgs/loading/load6.gif';this.onerror=null" >
<img src="" lazy-data-src="/img/3.png" onerror="this.src='/imgs/loading/load6.gif';this.onerror=null" >
<img src="" lazy-data-src="/img/4.png" onerror="this.src='/imgs/loading/load6.gif';this.onerror=null" >
<img src="" lazy-data-src="/img/5.png" onerror="this.src='/imgs/loading/load6.gif';this.onerror=null" >
<img src="" lazy-data-src="/img/6.png" onerror="this.src='/imgs/loading/load6.gif';this.onerror=null" >
</div>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
JS代码,
主要就是判断元素距离窗口顶部的距离,如果在可视区,就将属性替换属性,图片也就加载了。
一定情况提高了性能。
复制收展HTML//图片懒加载
$(function () {
// 第一次需要加载一次
lazyLoadImg();
$(window).scroll(lazyLoadImg);
//在可视区,需要记载为真
var incr = 15;
function isVisible(el) {
const bound = el.getBoundingClientRect(); //相对于视窗的位置集合。集合中有top, right, bottom, left等属性
const clientHeight = $(window).height(); // 可视区高度,窗口的高度
return bound.top <= clientHeight + incr; // +incr是为了提前加载。
}
//已加载为真
function isLoaded(el) {
var regex = "http"; //网图
var regex2 = "https"; //网图
var src = $(el).attr('src'); console.log(src)
if( src.indexOf(regex)> -1 || src.indexOf(regex2)> -1 ) return true;
else return false;
}
function lazyLoadImg() {
$.each($('#imgList img'), (index,item)=>{
//console.log(index + ">" + isVisible(item) + "====" + isLoaded(item) );
//没必要每次都替换,只需要替换未加载的
if(isVisible(item) && !isLoaded(item)) { //debugger
$(item).attr('src', $(item).attr('lazy-data-src'));
}
});
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32