写一个html文件,用原生js实现图片懒加载的源码
时间: 2024-05-19 09:12:36 浏览: 77
html图片懒加载
<!DOCTYPE html>
<html>
<head>
<title>Lazy Load Images</title>
</head>
<body>
<img data-src="https://via.placeholder.com/150" alt="Image 1">
<img data-src="https://via.placeholder.com/250" alt="Image 2">
<img data-src="https://via.placeholder.com/350" alt="Image 3">
<img data-src="https://via.placeholder.com/450" alt="Image 4">
<script>
function lazyLoad() {
let lazyImages = document.querySelectorAll('img[data-src]');
let options = {
rootMargin: '0px',
threshold: 0.1
}
let observer = new IntersectionObserver(function(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting) {
let image = entry.target;
image.src = image.dataset.src;
image.removeAttribute('data-src');
observer.unobserve(image);
}
});
}, options);
lazyImages.forEach(image => {
observer.observe(image);
});
}
window.addEventListener('load', lazyLoad);
</script>
</body>
</html>
阅读全文