懒加载逻辑
一般如果场景比较大,滚动条很长,图片比较多的情况下,不使用赖加载图片会一下子把资源都加载,导致性能很慢,甚至没有滚动到下面也加载了,很浪费资源 现在通过滚动事件来处理图片加载,我们先吧要显示的图片src
数据放到自定义属性上data-src
后面通过滚动事件把可见的区域的图片src
赋值上去
效果图
继续往下面滚动才加载
代码
<! DOCTYPE html >
< style>
.container {
height : 300px;
width : 300px;
overflow : auto;
}
.image {
width : 100%;
height : 100px;
margin : 10px 0;
}
</ style>
< body>
< div class = " container" > </ div>
</ body>
</ html>
< script>
const dom = document. querySelector ( '.container' )
for ( let i = 0 ; i < 10 ; i++ ) {
const img = document. createElement ( 'img' )
img. setAttribute ( 'data-src' , ` https://api.yimian.xyz/img?i= ${ i} ` )
img. className = 'image'
dom. appendChild ( img)
}
let list = document. querySelectorAll ( '.image' )
const handleScroll = ( ) => {
for ( let i = 0 ; i < list. length; i++ ) {
var rect = list[ i] . getBoundingClientRect ( ) ;
if ( dom. scrollTop > rect. top) {
list[ i] . src = list[ i] . getAttribute ( 'data-src' )
}
}
if ( [ ... list] . every ( ( item ) => {
return item. src
} ) ) {
dom. removeEventListener ( 'scroll' , handleScroll)
}
}
dom. addEventListener ( 'scroll' , handleScroll)
for ( let i = 0 ; i < list. length; i++ ) {
var rect = list[ i] . getBoundingClientRect ( ) ;
if ( dom. clientHeight > rect. top) {
list[ i] . src = list[ i] . getAttribute ( 'data-src' )
}
}
</ script>