当前位置:网站首页>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>
边栏推荐
- Nodejs Foundation: shallow chat URL and querystring module
- How to execute a swift for in loop in one step- How can I do a Swift for-in loop with a step?
- 递归:深度优先搜索
- pytorch开源吗?
- Nat. Comm. | 使用Tensor-cell2cell对细胞通讯进行环境感知去卷积
- DAPP for getting started with eth
- Introduction to eth
- SAP UI5 应用开发教程之一百零五 - SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
- Message queue addition failure
- Read a paper_ ChineseBert
猜你喜欢
[brush questions] find the number pair distance with the smallest K
Simple wechat applet development page Jump, data binding, obtaining user information, obtaining user location information
[embedded module] OLED display module
学会pytorch能干什么?
CVPR 2022 | 大連理工提出自校准照明框架,用於現實場景的微光圖像增强
在 .NET 6 项目中使用 Startup.cs
2022 tea master (primary) examination questions and tea master (primary) examination question bank
【刷题篇】 找出第 K 小的数对距离
2022 Shandong Province safety officer C certificate examination questions and Shandong Province safety officer C certificate simulation examination question bank
没有sXid,suid&sgid将进入险境!-尚文网络xUP楠哥
随机推荐
NPM: the 'NPM' item cannot be recognized as the name of a cmdlet, function, script file, or runnable program. Please check the spelling of the name. If the path is included, make sure the path is corr
[national programming] [software programming - Lecture Video] [zero foundation introduction to practical application]
Error in compiled file: error: unmapped character encoding GBK
The 10th China Cloud Computing Conference · China Station: looking forward to the trend of science and technology in the next decade
递归:深度优先搜索
Recursive use and multi-dimensional array object to one-dimensional array object
Ffmpeg recording screen and screenshot
Nodejs Foundation: shallow chat URL and querystring module
Separable bonds and convertible bonds
105. Detailed introduction of linkage effect realization of SAP ui5 master detail layout mode
QSAR model establishment script based on pytoch and rdkit
【DRM】DRM bridge驱动调用流程简单分析
pytorch开源吗?
Filter
递归:快速排序,归并排序和堆排序
C language hashtable/hashset library summary
How to execute a swift for in loop in one step- How can I do a Swift for-in loop with a step?
js/ts底层实现双击事件
递归:一维链表和数组
2022 tea master (intermediate) examination questions and analysis and tea master (intermediate) practical examination video