看下tuniu的页面,这有两个属性src和data-src
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Lazy Load Images</title><style>/* Placeholder style */.placeholder {width: 300px;height: 200px;background-color: #ccc;display: flex;justify-content: center;align-items: center;}</style></head><body><!-- Placeholder for the image --><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><div class="placeholder">Loading...</div><!-- Actual image element with data-src attribute --><img data-src="https://img1.tuniucdn.com/site/images/yj_2016/init-img.jpg" alt="Lazy-loaded Image" id="lazy-image" /><script>// Function to lazy load the image when it comes into the viewportfunction lazyLoadImage() {var lazyImage = document.getElementById("lazy-image");var scrollTop =window.pageYOffset ||(document.documentElement ||document.body.parentNode ||document.body).scrollTop;var windowHeight = window.innerHeight;var imageOffsetTop = lazyImage.getBoundingClientRect().top + scrollTop;if (imageOffsetTop < windowHeight + scrollTop) {// Image is in the viewport, load the imagelazyImage.src = lazyImage.getAttribute("data-src");// Remove the data-src attribute to prevent loading the image againlazyImage.removeAttribute("data-src");// Remove the event listener as the image is already loadedwindow.removeEventListener("scroll", lazyLoadImage);}}// Add event listener to lazy load the image when scrollingwindow.addEventListener("scroll", lazyLoadImage);// Initially trigger the lazy load function to check if the image is already in the viewportlazyLoadImage();</script></body>
</html>
页面滚动到图片的位置才会加载相应的图片