当前位置:网站首页>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>
边栏推荐
- [brush questions] find the number pair distance with the smallest K
- 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-07-02:以下go语言代码输出什么?A:编译错误;B:Panic;C:NaN。 package main import “fmt“ func main() { var a =
- Esp32 series (3): GPIO learning (take simple GPIO input and output, ADC, DAC as examples)
- Use of sigaction
- 树莓派如何连接WiFi
- 如何迈向IPv6之IPv6过渡技术-尚文网络奎哥
- [mathematical logic] predicate logic (first-order predicate logic formula | example)
- Commands related to the startup of redis under Linux server (installation and configuration)
- 深潜Kotlin协程(十九):Flow 概述
猜你喜欢

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

Hutool dynamically adds scheduled tasks

Recursion: quick sort, merge sort and heap sort

【刷题篇】接雨水(一维)

Nodejs Foundation: shallow chat URL and querystring module

300+篇文献!一文详解基于Transformer的多模态学习最新进展

JS native common knowledge

编译文件时报错:错误: 编码GBK的不可映射字符

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
随机推荐
Is pytorch open source?
Ffmpeg one / more pictures synthetic video
[brush questions] find the number pair distance with the smallest K
Dynamic programming: Longest palindrome substring and subsequence
What is pytorch? Is pytorch a software?
Appium自动化测试框架
Intercept string fixed length to array
ZIP文件的导出
2022 tea master (intermediate) examination questions and analysis and tea master (intermediate) practical examination video
Arlo's thinking about himself
js中#号的作用
nodejs基础:浅聊url和querystring模块
『期末复习』16/32位微处理器(8086)基本寄存器
[DRM] simple analysis of DRM bridge driver call process
leetcode:297. 二叉树的序列化与反序列化
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 =
Interface embedded in golang struct
[embedded module] OLED display module
105. Detailed introduction of linkage effect realization of SAP ui5 master detail layout mode
How to move towards IPv6: IPv6 Transition Technology - Shangwen network quigo