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

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

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

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

HTML代码

rush:xhtml;">

判断元素是否在可视区域

方法一:

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函数自动观察元素是否在可视区域内

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

js代码

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

rush: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

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程序设计有所帮助。

相关文章

什么是深拷贝与浅拷贝?深拷贝与浅拷贝是js中处理对象或数据...
前言 今天复习了一些前端算法题,写到一两道比较有意思的题:...
最近在看回JavaScript的面试题,this 指向问题是入坑前端必须...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面