当前位置:网站首页>图片懒加载的原理
图片懒加载的原理
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 是异步的,不随着目标元素的滚动同步触发。
边栏推荐
- Li Kou 98: verify binary search tree
- On-off and on-off of quality system construction
- NFT insider 64: e-commerce giant eBay submitted an NFT related trademark application, and KPMG will invest $30million in Web3 and metauniverse
- Redis入门完整教程:哈希说明
- md5工具类
- How can enterprises cross the digital divide? In cloud native 2.0
- 串口数据帧
- How to send a reliable request before closing the page
- Unity修仙手游 | lua动态滑动功能(3种源码具体实现)
- Analysis of environmental encryption technology
猜你喜欢

Google Earth Engine(GEE)——基于 MCD64A1 的 GlobFire 日常火灾数据集

Install the gold warehouse database of NPC

Sobel filter

NFT insider 64: e-commerce giant eBay submitted an NFT related trademark application, and KPMG will invest $30million in Web3 and metauniverse

Redis入门完整教程:HyperLogLog

Redis入门完整教程:Bitmaps

都说软件测试很简单有手就行,但为何仍有这么多劝退的?

The overview and definition of clusters can be seen at a glance

Logo special training camp section 1 Identification logo and logo design ideas

Redis入门完整教程:哈希说明
随机推荐
【lua】int64的支持
[cooking record] - stir fried 1000 pieces of green pepper
Microservices -- Opening
Advanced area of attack and defense world misc 3-11
High school physics: linear motion
Practice and principle of PostgreSQL join
醒悟的日子,我是怎么一步一步走向软件测试的道路
Logo Camp d'entraînement section 3 techniques créatives initiales
Three stage operations in the attack and defense drill of the blue team
模拟摇杆控制舵机
华泰证券是国家认可的券商吗?开户安不安全?
常用技术指标之一文读懂BOLL布林线指标
NFT Insider #64:电商巨头eBay提交NFT相关商标申请,毕马威将在Web3和元宇宙中投入3000万美元
企业如何跨越数字化鸿沟?尽在云原生2.0
The difference between Max and greatest in SQL
MySQL Architecture - user rights and management
Create Ca and issue certificate through go language
串口数据帧
Unity修仙手游 | lua动态滑动功能(3种源码具体实现)
攻防世界 misc 高手进阶区 a_good_idea