当前位置:网站首页>图片懒加载的方案
图片懒加载的方案
2022-07-05 10:21:00 【码小龙.】
图片懒加载的方案
前言
图片懒加载是前端性能提升的重要方面之一,其主要的用途是: 减少网络加载,提升体验。
但为了影响体验,你需要最好写好布局样式,最好写好占位图。
懒加载的原理
其实图片的加载主要是因为图片的src引起的,而如果我们想要实现懒加载,就避免src路径的加载即可,我们可以将图片的路径存储到data-src的自定义数据属性上,然后在需要的时候按需加载。
按需加载的实现方式有两种:这里重点说第一种,目前在移动端以及在pc的瀑布流布局中都是第一种居多。
1 滚动到页面底部加载
2 分页加载
滚动到页面底部加载的原理
原来的方式:滚动监听
其主要实现的原理是对滚动事件的监听,当发现滚动条高度+滚动条高度等于document的高度时,就是达到页面的底部了,需要重新加载图片的时机。
KaTeX parse error: Expected '}', got 'EOF' at end of input: …ction(){ if((window).scrollTop() + ( w i n d o w ) . h e i g h t ( ) > = (window).height()>= (window).height()>=(document).height()){
var $div = ‘
- append添加的节点
- ’;
KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲container').app…div)
}
});
新的方式:IntersectionObserver
我们去看下jq的lazyload的源码是如何写这部分函数的,核心是依赖IntersectionObserver,是检测元素是否进入视图,如果有进入,那么就会移除其lazy的class,其源码地址:链接
document.addEventListener(“DOMContentLoaded”, function() {
var lazyImages = [].slice.call(document.querySelectorAll(“img.lazy”));
if (“IntersectionObserver” in window) {
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.srcset = lazyImage.dataset.srcset;
lazyImage.classList.remove(“lazy”);
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
} else {
// Possibly fall back to a more compatible method here
}
});
边栏推荐
- [可能没有默认的字体]Warning: imagettfbbox() [function.imagettfbbox]: Invalid font filename……
- C function returns multiple value methods
- 小程序中自定义行内左滑按钮,类似于qq和wx消息界面那种
- Glide advanced level
- Learning notes 5 - high precision map solution
- LSTM应用于MNIST数据集分类(与CNN做对比)
- Glide conclusion
- AtCoder Beginner Contest 258「ABCDEFG」
- AtCoder Beginner Contest 258「ABCDEFG」
- AtCoder Beginner Contest 254「E bfs」「F st表维护差分数组gcd」
猜你喜欢
随机推荐
数据库中的范式:第一范式,第二范式,第三范式
pytorch输出tensor张量时有省略号的解决方案(将tensor完整输出)
Nine degrees 1480: maximum ascending subsequence sum (dynamic programming idea for the maximum value)
uniapp
Learning note 4 -- Key Technologies of high-precision map (Part 2)
Constrained layout flow
【tcp】服务器上tcp连接状态json形式输出
字符串、、
“军备竞赛”时期的对比学习
php解决redis的缓存雪崩,缓存穿透,缓存击穿的问题
Universal double button or single button pop-up
Livedata interview question bank and answers -- 7 consecutive questions in livedata interview~
学习笔记6--卫星定位技术(上)
[observation] with the rise of the "independent station" model of cross-border e-commerce, how to seize the next dividend explosion era?
SAP ui5 objectpagelayout control usage sharing
Solution of ellipsis when pytorch outputs tensor (output tensor completely)
脚手架开发进阶
@Serializedname annotation use
How do programmers live as they like?
到底谁才是“良心”国产品牌?