当前位置:网站首页>JS realizes lazy loading of pictures
JS realizes lazy loading of pictures
2022-07-03 04:04:00 【jingde528】
Recently, I need to build a small website , But what? , Because there are more pictures , Opening web pages is slow , The server will be under great pressure . It not only affects the rendering speed, but also wastes bandwidth , For example, a 1M Size picture , Concurrent , achieve 1000 Concurrent , That is, at the same time 1000 Personal visit , It will produce 1 individual G The bandwidth of the . So I thought of lazy image loading to reduce the pressure on the server , Load the content of the visual area first , Other parts are loaded after entering the visual area , To improve performance , It can greatly improve the loading speed of web pages , The effect is obvious , So I thought about recording this method , Convenient for later use or people in need , Methods and functions are available for personal testing .
One 、 principle
First the img Labeled src Link to same picture ( It's usually loading.gif picture ), And then to img label Set custom properties ( data-src), Then store the real picture address in data-src in , When JS When listening to the image element entering the visual window , Store the address in the custom attribute in src Properties of the . Achieve the effect of lazy loading . This prevents the page from sending a large number of requests to the server at one time , Result in server response surface , Page jam crash, etc .
Two 、 Realization
Webpage loading.gif material : 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>
// Depend on jquery
<script>
// When there is no scrolling at first , The image that appears in the window will also be loaded
start();
// When the page starts scrolling , Traverse images , If the picture appears in the window , Just load the picture
var clock; // Function throttling
$(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));
}
})
}
// Function to determine whether the picture appears in the window
//$node.offset().top by $node Offset value to the top of the document
//$(window).scrollTop() The distance from the scroll bar to the top of the window
//$(window).height()+$(window).scrollTop(); Visual window
//JQ Of offset().top And js Of offsetTop Detailed explanation
function isShow($node){
return $node.offset().top <= $(window).height()+$(window).scrollTop();
}
// Functions for loading pictures , That is to put custom attributes data-src The real picture address stored , Assign a value to src
function loadImg($img){
$img.attr('src', $img.attr('data-src'));
// Already loaded pictures , I set a property for it , The value is 1, As identification
// The original intention of doing this is because , Every time you scroll , All the pictures will be traversed , This is a bit wasteful , So make a sign , When scrolling, only traverse the pictures that have not been loaded
$img.attr('data-isLoading',1);
}
</script>
3、 ... and 、 You can also use lazysizes No matter how lazy the plug-in is , Details refer to :Lazysizes.js How to use lazy image loading or 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>
边栏推荐
- Arduino application development - LCD display GIF dynamic diagram
- How does the pytorch project run?
- js实现在可视区内,文字图片动画效果
- Mila、渥太华大学 | 用SE(3)不变去噪距离匹配进行分子几何预训练
- 以两列的瀑布流为例,我们应该怎么构建每一列的数组
- Analysis of the reason why the server cannot connect remotely
- pytorch是什么?pytorch是一个软件吗?
- Appium自动化测试框架
- Null and undefined
- Wechat applet + Alibaba IOT platform + Hezhou air724ug build a serverless IOT system (III) -- wechat applet is directly connected to Alibaba IOT platform aliiot
猜你喜欢
Wechat applet + Alibaba IOT platform + Hezhou air724ug built with server version system analysis
有监督预训练!文本生成又一探索!
学会pytorch能干什么?
Download and install captura and configure ffmpeg in captura
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
JS native common knowledge
CVPR 2022 | 大連理工提出自校准照明框架,用於現實場景的微光圖像增强
Supervised pre training! Another exploration of text generation!
nodejs基础:浅聊url和querystring模块
[Apple Photo Album push] IMessage group anchor local push
随机推荐
The longest subarray length with a positive product of 1567 recorded by leecode
[mathematical logic] predicate logic (judge whether the first-order predicate logic formula is true or false | explain | example | predicate logic formula type | forever true | forever false | satisfi
Is pytorch open source?
2022deepbrainchain biweekly report no. 104 (01.16-02.15)
JS实现图片懒加载
MPLS setup experiment
Leecode swipe questions and record LCP 18 breakfast combination
pytorch难学吗?如何学好pytorch?
深潜Kotlin协程(十九):Flow 概述
Hutool dynamically adds scheduled tasks
2022-07-02:以下go语言代码输出什么?A:编译错误;B:Panic;C:NaN。 package main import “fmt“ func main() { var a =
SAP UI5 应用开发教程之一百零五 - SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
IPv6过渡技术-6to4手工隧道配置实验--尚文网络奎哥
[Blue Bridge Road - bug free code] pcf8591 - code analysis of AD conversion
For instruction, uploading pictures and display effect optimization of simple wechat applet development
How to connect WiFi with raspberry pie
Wechat applet + Alibaba IOT platform + Hezhou air724ug build a serverless IOT system (III) -- wechat applet is directly connected to Alibaba IOT platform aliiot
Half of 2022 is over, so we must hurry up
[learning notes] seckill - seckill project - (11) project summary
105. Detailed introduction of linkage effect realization of SAP ui5 master detail layout mode