您的位置:首页 > Web前端 > JavaScript

JavaScript实现图片懒加载的方法分析

2018-07-05 09:23 781 查看

本文实例讲述了JavaScript实现图片懒加载的方法。分享给大家供大家参考,具体如下:

懒加载是非常实用的提升网页性能的方式,当访问一个页面的时候,只显示可视区域内的图片,其它的图片只有出现在可视区域内的时候才会被请求加载。

我们现在用原生的js实现简单的图片懒加载,主要利用的原理就是先不给设置src,而是把图片的路径放在data-src中,等待图片被加载的时候将路径取出放到src中。

HTML代码

<div class="container">
<div class="img-area">
<img class="my-photo" alt="loading" data-src="img/img1.png">
</div>
<div class="img-area">
<img class="my-photo" alt="loading" data-src="img/img2.png">
</div>
<div class="img-area">
<img class="my-photo" alt="loading" data-src="img/img3.png">
</div>
<div class="img-area">
<img class="my-photo" alt="loading" data-src="img/img4.png">
</div>
<div class="img-area">
<img class="my-photo" alt="loading" data-src="img/img5.png">
</div>
</div>

判断元素是否在可视区域

方法一:

1. 获取屏幕可视区高度:

document.documentElement.clientHeight

2. 获取元素距顶部的高度:
element.offsetTop

3. 获取滚动高度:
document.documentElement.scrollTop

4. 若满足:2-3<1,那么元素就出现在可视区域

方法二:

1. 获取元素到可视区域顶部的距离:

var bound = element.getBoundingClientRect()

2. 获取可视区域的高度:
window.innerHeight

3. 若满足
bound.top<=window.innerHeight
,那么元素就出现在可视区域

方法三:

利用

IntersectionObserver
函数自动观察元素是否在可视区域内

var watch = new IntersectionObserver(callback,option);
//开始观察
watch.observe(el);
//停止观察
watch.unobserve(el);
//关闭观察器
watch.disconnect();

js代码

第一种很多人都用过,所以我们就用第二种写一下

//判断图片是否出现在可视区域内
function isInSight(el) {
const bound = el.getBoundingClientRect();
const clientHeight = window.innerHeight;
return bound.top <= clientHeight + 100;
}
//加载图片
let index = 0;
function checkImgs() {
const imgs = document.querySelectorAll('.my-photo');
for( let i = index; i < imgs.length; i++){
if(isInSight(imgs[i])){
loadImg(imgs[i]);
index = i;
}
}
}
function loadImg(el) {
if(!el.src){
const source = el.dataset.src;
el.src = source;
}
}
//函数节流
//函数节流是很重要的思想,可以防止过于频繁的操作dom
function throttle(fn,mustRun = 500) {
const timer = null;
let previous = null;
return function () {
const now = new Date();
const context = this;
const args = arguments;
if(!previous){
previous = now;
}
const remaining = now -previous;
if(mustRun && remaining >= mustRun){
fn.apply(context,args);
previous = now;
}
}
}
//调用函数
window.onload=checkImgs;
window.onscroll = throttle(checkImgs);

我们在用第三种方法写一个demo

function checkImgs() {
const imgs = Array.from(document.querySelectorAll(".my-photo"));
imgs.forEach(item => io.observe(item));
}
function loadImg(el) {
if (!el.src) {
const source = el.dataset.src;
el.src = source;
}
}
const io = new IntersectionObserver(ioes => {
ioes.forEach(ioe => {
const el = ioe.target;
const intersectionRatio = ioe.intersectionRatio;
if (intersectionRatio > 0 && intersectionRatio <= 1) {
loadImg(el);
}
el.onload = el.onerror = () => io.unobserve(el);
});
});

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript图片操作技巧大全》、《JavaScript运动效果与技巧汇总》、《JavaScript切换特效与技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结

希望本文所述对大家JavaScript程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息