当前位置:网站首页>JS实现图片懒加载
JS实现图片懒加载
2022-07-03 04:00:00 【jingde528】
最近因为需要做一个小网站,但是呢,因为图片比较多,打开网页速度很慢,服务器压力就会很大。不仅影响渲染速度还会浪费带宽,比如一个1M大小的图片,并发情况下,达到1000并发,即同时有1000个人访问,就会产生1个G的带宽。于是就想到了图片懒加载来减轻服务器的压力,优先加载可视区域的内容,其他部分等进入了可视区域再加载,从而提高性能,可以大幅度的提高网页加载速度,效果很明显,于是想着将这个方法记录下来,方便以后或者有需要的人使用,方法和功能都是亲测可用。
一、原理
先将 img 标签的 src 链接设为同一张图片(一般是loading.gif图片),然后给 img标签 设置自定义属性( data-src),然后将真正的图片地址存储在 data-src 中,当JS监听到该图片元素进入可视窗口时,将自定义属性中的地址存储到src属性中。达到懒加载的效果。这样做能防止页面一次性向服务器发送大量请求,导致服务器响应面,页面卡顿崩溃等。
二、实现
网页loading.gif 素材 : http://www.sucaijishi.com/2013/gif_0527/57.html
<a href="javascript:;" class="img" rel="nofollow" >
<img src="/static/images/utils/loading.gif" th:data-src="${goodList.goodsImg}">
</a>
// 需依赖jquery

<script>
// 一开始没有滚动的时候,出现在视窗中的图片也会加载
start();
// 当页面开始滚动的时候,遍历图片,如果图片出现在视窗中,就加载图片
var clock; //函数节流
$(window).on('scroll',function(){
if(clock){
clearTimeout(clock);
}
clock = setTimeout(function(){
start()
},200)
})
function start(){
$('.img img').not('[data-isLoading]').each(function () {
if (isShow($(this))) {
loadImg($(this));
}
})
}
// 判断图片是否出现在视窗的函数
//$node.offset().top 为$node到文档顶部的偏移值
//$(window).scrollTop() 滚动条到窗口顶部的距离
//$(window).height()+$(window).scrollTop(); 可视窗口
//JQ的offset().top与js的offsetTop区别详解
function isShow($node){
return $node.offset().top <= $(window).height()+$(window).scrollTop();
}
// 加载图片的函数,就是把自定义属性data-src 存储的真正的图片地址,赋值给src
function loadImg($img){
$img.attr('src', $img.attr('data-src'));
// 已经加载的图片,我给它设置一个属性,值为1,作为标识
// 弄这个的初衷是因为,每次滚动的时候,所有的图片都会遍历一遍,这样有点浪费,所以做个标识,滚动的时候只遍历哪些还没有加载的图片
$img.attr('data-isLoading',1);
}
</script>
三、也可以使用lazysizes插件实再懒加载,详情参考:Lazysizes.js 图片懒加载的使用方法详解 或 lazysizes/README.md at gh-pages · aFarkas/lazysizes · GitHub
<div class="img-wrap">
<img class="lazyload" data-src="https://14528923.s61i.faiusr.com/4/AD0Im_P2BhAEGAAgsojEzAUoyvSs1AIwqwM4qgM.png.webp" />
<img class="lazyload" data-src="https://www.colamark.cn/images/guest02.jpg" />
</div>
<script src="http://afarkas.github.io/lazysizes/lazysizes.min.js"></script>
边栏推荐
- [learning notes] seckill - seckill project - (11) project summary
- js中#号的作用
- [brush questions] most elements (super water king problem)
- 中移物联网OneOS与OneNET入选《2021年物联网示范项目名单》
- 2022deepbrainchain biweekly report no. 104 (01.16-02.15)
- QSAR model establishment script based on pytoch and rdkit
- [Apple Photo Album push] IMessage group anchor local push
- IPv6 transition technology-6to4 manual tunnel configuration experiment -- Kuige of Shangwen network
- sigaction的使用
- leetcode:动态规划模板
猜你喜欢

IPv6过渡技术-6to4手工隧道配置实验--尚文网络奎哥

2022 polymerization process examination questions and polymerization process examination skills

In Net 6 project using startup cs
![[brush questions] connected with rainwater (one dimension)](/img/21/318fcb444b17be887562f4a9c1fac2.png)
[brush questions] connected with rainwater (one dimension)

2022 P cylinder filling examination content and P cylinder filling practice examination video

Is it better to speculate in the short term or the medium and long term? Comparative analysis of differences

Esp32 series (3): GPIO learning (take simple GPIO input and output, ADC, DAC as examples)

What is pytorch? Is pytorch a software?

TCP/IP模型中的重磅嘉宾TCP--尚文网络奎哥

『期末复习』16/32位微处理器(8086)基本寄存器
随机推荐
JS native common knowledge
Shardingsphere dynamic data source
ZIP文件的导出
树莓派如何连接WiFi
Is pytorch open source?
2022deepbrainchain biweekly report no. 104 (01.16-02.15)
递归:深度优先搜索
Application of I2C protocol of STM32F103 (read and write EEPROM)
The 10th China Cloud Computing Conference · China Station: looking forward to the trend of science and technology in the next decade
【刷题篇】多数元素(超级水王问题)
可分离债券与可转债
leetcode:动态规划模板
105. SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
[home push IMessage] software installation virtual host rental tothebuddy delay
Web session management security issues
Recursion: one dimensional linked lists and arrays
动态规划:最长公共子串和最长公共子序列
[Blue Bridge Road - bug free code] pcf8591 - code analysis of AD conversion
300+篇文献!一文详解基于Transformer的多模态学习最新进展
CVPR 2022 | 大連理工提出自校准照明框架,用於現實場景的微光圖像增强