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>
|