intersectionObserver实现图片懒加载

tech2026-03-31  9

图片懒加载

图片懒加载的目的: 更加快速的加来页面,减少不必要的资源浪费。

简单代码实现

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .w { height: 500px; width: 1200px; transform: translateX(120px); opacity: 0.5; transition: all 1s; } .animate1 { opacity: 1; transform: translateX(00px); } </style> </head> <body> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <img src="./img2.png" data-img="./img1.png" alt="" class="w"> <!-- //data-img中保存的是要展示的图片地址 src为默认图片 --> <img src="./img2.png" data-img="./img1.png" alt="" class="w"> </body> <script> var intersectionObserver = new IntersectionObserver( function (entries, observer) { entries.forEach((item, index) => { if (item.isIntersecting) { //进入可视区为true item.target.setAttribute('src', item.target.getAttribute('data-img')); //加载图片 item.target.classList.add('animate1'); observer.unobserve(item.target) //解除当前元素的监听 console.log('Loaded new items'); console.log(item.intersectionRect); } }) }); // 开始观察 document.querySelectorAll('img').forEach((item, index) => { intersectionObserver.observe(item); }) </script> </html>

兼容性考虑 https://github.com/w3c/IntersectionObserver/tree/master/polyfill

MDN https://developer.mozilla.org/zh-CN/docs/Web/API/Intersection_Observer_API

最新回复(0)