动态监听滚动条事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!DOCTYPE html>
<html>
<head>
<title>Scroll Listener Image Lazy Loading</title>
<style>
img {
width: 100%;
height: auto;
display: block;
margin-bottom: 20px;
}
</style>
</head>
<body>
<h1>Scroll Listener Image Lazy Loading</h1>
<img data-src="https://picsum.photos/id/1015/600/400" alt="Image 1">
<img data-src="https://picsum.photos/id/1016/600/400" alt="Image 2">
<img data-src="https://picsum.photos/id/1018/600/400" alt="Image 3">
<img data-src="https://picsum.photos/id/1020/600/400" alt="Image 4">
<img data-src="https://picsum.photos/id/1021/600/400" alt="Image 5">

<script>
const images = document.querySelectorAll('img[]');

function lazyLoad() {
images.forEach(image => {
const rect = image.getBoundingClientRect();
if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
const src = image.getAttribute('data-src');
image.setAttribute('src', src);
// image.removeAttribute('data-src'); // 增加这行会导致并行触发覆盖的bug
}
});
}

window.addEventListener('scroll', lazyLoad);
</script>
</body>
</html>

通过IntersectionObserver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html>
<head>
<title>Intersection Observer Image Lazy Loading</title>
<style>
img {
width: 100%;
height: 1200px;
display: block;
margin-bottom: 20px;
}
</style>
</head>
<body>
<h1>Intersection Observer Image Lazy Loading</h1>
<img data-src="https://picsum.photos/id/1015/600/400" alt="Image 1">
<img data-src="https://picsum.photos/id/1016/600/400" alt="Image 2">
<img data-src="https://picsum.photos/id/1018/600/400" alt="Image 3">
<img data-src="https://picsum.photos/id/1020/600/400" alt="Image 4">
<img data-src="https://picsum.photos/id/1021/600/400" alt="Image 5">

<script>
const images = document.querySelectorAll('img');

const options = {
root: null,
rootMargin: '0px',
threshold: 0.5
}

const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
const src = img.getAttribute('data-src');
img.setAttribute('src', src);
observer.unobserve(img);
}
})
}, options);

images.forEach(image => {
observer.observe(image);
});
</script>
</body>
</html>