当前位置:网站首页>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>
边栏推荐
- Practical operation of vim
- pytorch项目怎么跑?
- IPv6过渡技术-6to4手工隧道配置实验--尚文网络奎哥
- 学会pytorch能干什么?
- JMeter starts from zero (III) -- simple use of regular expressions
- Social phobia of contemporary young people (III)
- 树莓派如何连接WiFi
- Half of 2022 is over, so we must hurry up
- Idea shortcut keys
- Debug: CD cannot be used in kaggle
猜你喜欢

毕设-基于SSM宠物领养中心

递归:快速排序,归并排序和堆排序

Nodejs Foundation: shallow chat URL and querystring module

IPv6 transition technology-6to4 manual tunnel configuration experiment -- Kuige of Shangwen network

2022 tea master (primary) examination questions and tea master (primary) examination question bank

JS native common knowledge

Recursion: quick sort, merge sort and heap sort

Makefile demo
![[brush questions] most elements (super water king problem)](/img/79/13a715b74bc18a4a62113de76a65f6.png)
[brush questions] most elements (super water king problem)

有监督预训练!文本生成又一探索!
随机推荐
Web会话管理安全问题
Dynamic programming: Longest palindrome substring and subsequence
[home push IMessage] software installation virtual host rental tothebuddy delay
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
Shardingsphere dynamic data source
DAPP for getting started with eth
[brush questions] connected with rainwater (one dimension)
『期末复习』16/32位微处理器(8086)基本寄存器
JS native common knowledge
2022-07-02:以下go语言代码输出什么?A:编译错误;B:Panic;C:NaN。 package main import “fmt“ func main() { var a =
Half of 2022 is over, so we must hurry up
China Mobile Internet of things oneos and onenet were selected in the list of 2021 Internet of things demonstration projects
Recursive use and multi-dimensional array object to one-dimensional array object
有监督预训练!文本生成又一探索!
【全民编程】《软件编程-讲课视频》【零基础入门到实战应用】
[mathematical logic] propositional logic (propositional logic reasoning | formal structure of reasoning | inference law | additional law | simplification law | hypothetical reasoning | refusal | disju
[Blue Bridge Road -- bug free code] DS18B20 temperature reading code analysis
In Net 6 project using startup cs
[national programming] [software programming - Lecture Video] [zero foundation introduction to practical application]
SAP UI5 应用开发教程之一百零五 - SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍