当前位置:网站首页>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>
边栏推荐
- 【刷题篇】多数元素(超级水王问题)
- 释放数据力量的Ceph-尚文网络xUP楠哥
- Is pytorch open source?
- Recursive use and multi-dimensional array object to one-dimensional array object
- Introduction to eth
- Appium自动化测试框架
- Supervised pre training! Another exploration of text generation!
- leetcode:297. 二叉树的序列化与反序列化
- [brush questions] most elements (super water king problem)
- Commands related to the startup of redis under Linux server (installation and configuration)
猜你喜欢
China Mobile Internet of things oneos and onenet were selected in the list of 2021 Internet of things demonstration projects
Wechat applet + Alibaba IOT platform + Hezhou air724ug built with server version system analysis
SAP UI5 应用开发教程之一百零五 - SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
Causal AI, a new paradigm for industrial upgrading of the next generation of credible AI?
JS实现图片懒加载
2022 polymerization process examination questions and polymerization process examination skills
300+篇文献!一文详解基于Transformer的多模态学习最新进展
毕设-基于SSM宠物领养中心
CVPR 2022 | 大连理工提出自校准照明框架,用于现实场景的微光图像增强
js实现在可视区内,文字图片动画效果
随机推荐
2022 mobile crane driver examination registration and mobile crane driver operation examination question bank
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
因果AI,下一代可信AI的产业升级新范式?
类的基础语法
What is pytorch? Is pytorch a software?
[brush questions] find the number pair distance with the smallest K
Intercept string fixed length to array
2022-07-02: what is the output of the following go language code? A: Compilation error; B:Panic; C:NaN。 package main import “fmt“ func main() { var a =
TCP, the heavyweight guest in tcp/ip model -- Kuige of Shangwen network
DAPP for getting started with eth
服务器无法远程连接原因分析
[Blue Bridge Road -- bug free code] DS18B20 temperature reading code analysis
[mathematical logic] predicate logic (first-order predicate logic formula | example)
Error c2694 "void logger:: log (nvinfer1:: ilogger:: severity, const char *)": rewrite the restrictive exception specification of virtual functions than base class virtual member functions
有监督预训练!文本生成又一探索!
Recursion: depth first search
Social phobia of contemporary young people (II)
C language hashtable/hashset library summary
What is the correct way to compare ntext columns with constant values- What's the right way to compare an NTEXT column with a constant value?
JMeter starts from zero (III) -- simple use of regular expressions