当前位置:网站首页>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>
边栏推荐
- Ffmpeg one / more pictures synthetic video
- [DRM] simple analysis of DRM bridge driver call process
- Interaction free shell programming
- Dynamic programming: longest common substring and longest common subsequence
- For instruction, uploading pictures and display effect optimization of simple wechat applet development
- How to download pytorch? Where can I download pytorch?
- SAP UI5 应用开发教程之一百零五 - SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
- MPLS setup experiment
- Debug: CD cannot be used in kaggle
- [Blue Bridge Road - bug free code] pcf8591 - code analysis of AD conversion
猜你喜欢

The latest analysis of the main principals of hazardous chemical business units in 2022 and the simulated examination questions of the main principals of hazardous chemical business units
![[brush questions] most elements (super water king problem)](/img/79/13a715b74bc18a4a62113de76a65f6.png)
[brush questions] most elements (super water king problem)

npm : 无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。

CVPR 2022 | 大連理工提出自校准照明框架,用於現實場景的微光圖像增强

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

Ffmpeg recording screen and screenshot

中移物联网OneOS与OneNET入选《2021年物联网示范项目名单》

Bisher - based on SSM pet adoption center

Arduino application development - LCD display GIF dynamic diagram

For instruction, uploading pictures and display effect optimization of simple wechat applet development
随机推荐
[embedded module] OLED display module
Write it down once Net travel management background CPU Explosion Analysis
SAP ui5 application development tutorial 105 - detailed introduction to the linkage effect implementation of SAP ui5 master detail layout mode
2022deepbrainchain biweekly report no. 104 (01.16-02.15)
Shardingsphere dynamic data source
C language hashtable/hashset library summary
Error c2694 "void logger:: log (nvinfer1:: ilogger:: severity, const char *)": rewrite the restrictive exception specification of virtual functions than base class virtual member functions
Interaction free shell programming
2022 mobile crane driver examination registration and mobile crane driver operation examination question bank
js中#号的作用
[mathematical logic] propositional logic (equivalent calculus | idempotent law | exchange law | combination law | distribution law | De Morgan law | absorption rate | zero law | identity | exclusion l
TCP/IP模型中的重磅嘉宾TCP--尚文网络奎哥
[Apple Photo Album push] IMessage group anchor local push
毕设-基于SSM宠物领养中心
没有sXid,suid&sgid将进入险境!-尚文网络xUP楠哥
pytorch项目怎么跑?
For instruction, uploading pictures and display effect optimization of simple wechat applet development
树莓派如何连接WiFi
Social phobia of contemporary young people (III)
China Mobile Internet of things oneos and onenet were selected in the list of 2021 Internet of things demonstration projects