当前位置:网站首页>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>
边栏推荐
- [mathematical logic] predicate logic (first-order predicate logic formula | example)
- 2022 mobile crane driver examination registration and mobile crane driver operation examination question bank
- How does the pytorch project run?
- [DRM] simple analysis of DRM bridge driver call process
- js实现在可视区内,文字图片动画效果
- Practical operation of vim
- How to connect WiFi with raspberry pie
- 『期末复习』16/32位微处理器(8086)基本寄存器
- [mathematical logic] propositional logic (judgment of the correctness of propositional logic reasoning | formal structure is eternal truth - equivalent calculus | deduction from premise - logical reas
- pytorch开源吗?
猜你喜欢
When writing a web project, SmartUpload is used for file upload and new string () is used for transcoding, but in the database, there will still be random codes similar to poker
IPv6 transition technology-6to4 manual tunnel configuration experiment -- Kuige of Shangwen network
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
[Apple Photo Album push] IMessage group anchor local push
[Apple Push] IMessage group sending condition document (push certificate) development tool pushnotification
2022 tea master (intermediate) examination questions and analysis and tea master (intermediate) practical examination video
Ffmpeg recording screen and screenshot
Wechat applet + Alibaba IOT platform + Hezhou air724ug built with server version system analysis
SAP ui5 application development tutorial 105 - detailed introduction to the linkage effect implementation of SAP ui5 master detail layout mode
Arduino application development - LCD display GIF dynamic diagram
随机推荐
Interaction free shell programming
阿洛对自己的思考
QSAR model establishment script based on pytoch and rdkit
Introduction to eth
竞品分析撰写
2022-07-02:以下go语言代码输出什么?A:编译错误;B:Panic;C:NaN。 package main import “fmt“ func main() { var a =
Nodejs Foundation: shallow chat URL and querystring module
[DRM] simple analysis of DRM bridge driver call process
Error c2694 "void logger:: log (nvinfer1:: ilogger:: severity, const char *)": rewrite the restrictive exception specification of virtual functions than base class virtual member functions
2022年已过半,得抓紧
MySQL create table
[Apple Push] IMessage group sending condition document (push certificate) development tool pushnotification
Wechat applet + Alibaba IOT platform + Hezhou air724ug build a serverless IOT system (III) -- wechat applet is directly connected to Alibaba IOT platform aliiot
深潜Kotlin协程(二十):构建 Flow
学会pytorch能干什么?
JS实现图片懒加载
Recursion: quick sort, merge sort and heap sort
Nat. Comm. | use tensor cell2cell to deconvolute cell communication with environmental awareness
以两列的瀑布流为例,我们应该怎么构建每一列的数组
【刷题篇】接雨水(一维)