当前位置:网站首页>图片懒加载的原理
图片懒加载的原理
2022-07-04 22:29:00 【前端扫地僧】
图片懒加载是什么
类似于大型的淘宝京东等网页,有大量的商品图片信息,如果我们使页面包含的所有图片一次性加载完成,加载速度回非常慢那用户体验很差。
目前流行的做法是滚动动态加载,也就是懒加载,显示在屏幕之外的图片默认不加载,随着页面的滚动,图片进入了显示的范围,则触发图片的加载显示,通常配合骨架屏来使用。
这样做的好处,一是页面加载速度快,而是节省流量,因为很少有用户会把页面从上到下滚动完。
图片懒加载的原理
先将img标签的src链接设为同一张图片(默认图片),当js监听到该图片进入可视窗口时,再将实际地址应用。
方法1
传统的实现方法是,监听到scroll事件后,调用目标元素(绿色方块)的getBoundingClientRect()方法,得到它对应于视口左上角的坐标,再判断是否在视口之内。这种方法的缺点是,由于scroll事件密集发生,计算量很大,容易造成性能问题。
获取可视窗口的大小,判断交叉面积
如果图片出现在视口就显示,赋值src
方法2
新的 IntersectionObserver API,可以自动"观察"元素是否可见,Chrome 51+ 已经支持。由于可见(visible)的本质是,目标元素与视口产生一个交叉区,所以这个 API 叫做"交叉观察器"。
IntersectionObserver是浏览器原生提供的构造函数,接受两个参数:callback是可见性变化时的回调函数,option是配置对象(该参数可选)。
IntersectionObserverEntry对象提供目标元素的信息,一共有六个属性。
time:可见性发生变化的时间,是一个高精度时间戳,单位为毫秒
target:被观察的目标元素,是一个 DOM 节点对象
rootBounds:根元素的矩形区域的信息,getBoundingClientRect()方法的返回值,如果没有根元素(即直接相对于视口滚动),则返回null
boundingClientRect:目标元素的矩形区域的信息
intersectionRect:目标元素与视口(或根元素)的交叉区域的信息
intersectionRatio:目标元素的可见比例,即intersectionRect占boundingClientRect的比例,完全可见时为1,完全不可见时小于等于0
IntersectionObserver API 是异步的,不随着目标元素的滚动同步触发。
边栏推荐
- 攻防世界 MISC 高手进阶区 001 normal_png
- leetcode 72. Edit distance edit distance (medium)
- Unity vscode emmylua configuration error resolution
- Serial port data frame
- 攻防世界 MISC 进阶区 Erik-Baleog-and-Olaf
- Logo special training camp Section IV importance of font design
- High school physics: linear motion
- 浅聊一下中间件
- LOGO特训营 第四节 字体设计的重要性
- Shell script implements application service log warehousing MySQL
猜你喜欢
Close system call analysis - Performance Optimization
It is said that software testing is very simple, but why are there so many dissuasions?
Redis入门完整教程:初识Redis
Google Earth Engine(GEE)——Tasks升级,实现RUN ALL可以一键下载任务类型中的所有影像
Mongodb aggregation operation summary
共创软硬件协同生态:Graphcore IPU与百度飞桨的“联合提交”亮相MLPerf
质量体系建设之路的分分合合
How to send a reliable request before closing the page
SPSS安装激活教程(包含网盘链接)
Serial port data frame
随机推荐
Locust performance test - environment construction and use
Google Earth Engine(GEE)——以MODIS/006/MCD19A2为例批量下载逐天AOD数据逐天的均值、最大值、最小值、标准差、方差统计分析和CSV下载(北京市各区为例)
Hit the core in the advanced area of misc in the attack and defense world
9 - 类
It is said that software testing is very simple, but why are there so many dissuasions?
PostgreSQL server programming aggregation and grouping
测试必会:BUG的分类及推进解决
[Lua] Int64 support
Serial port data frame
High school physics: linear motion
Deployment of JVM sandbox repeater
Advanced area of attack and defense world misc 3-11
The table is backed up in ODPs. Why check m in the metabase_ Table, the logical sizes of the two tables are inconsistent, but the number of
Unity-VScode-Emmylua配置报错解决
Erik baleog and Olaf, advanced area of misc in the attack and defense world
新版判断PC和手机端代码,手机端跳转手机端,PC跳转PC端最新有效代码
Create Ca and issue certificate through go language
Logo special training camp section II collocation relationship between words and graphics
攻防世界 MISC 进阶区 hong
MD5 tool class