js-review/html/懒加载优化.html
2024-05-20 14:32:05 +08:00

76 lines
3.3 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lazy Loading Random Images</title>
<style>
.image-container {
display: flex;
flex-wrap: wrap;
gap: 10px;
justify-content: center;
padding: 20px;
}
img {
display: block;
width: 300px;
height: 200px;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<h2>Scroll down to load images</h2>
<div class="image-container" id="image-container"></div>
<script>
document.addEventListener("DOMContentLoaded", function() {
const imageContainer = document.getElementById('image-container');
const imageUrls = [
'https://blog-icoding.ddnsto.com/upload/b178e0eaa1516fe27b3babd932aa37cc80b17472.jpg@942w_930h_progressive.jpeg',
'https://blog-icoding.ddnsto.com/upload/f892d57fedb12065c2b1379eb6f193ab91e9b364.jpg@942w_936h_progressive.jpeg',
'https://blog-icoding.ddnsto.com/upload/710827654220b2e2418aa9b24838974ea8b0f9fd.jpg@942w_921h_progressive.jpeg',
'https://blog-icoding.ddnsto.com/upload/8e5e9700d916e69f69c79cdb5f525d67ee9a3f0d.jpg@942w_927h_progressive.jpeg',
'https://blog-icoding.ddnsto.com/upload/39ab275203860c6fdfaa58d061cc262c7618a459.jpg@942w_923h_progressive.jpeg',
'https://blog-icoding.ddnsto.com/upload/c73b288188420cdc89ab913975fee837c79a058f.jpg@942w_927h_progressive.jpeg',
'https://blog-icoding.ddnsto.com/upload/5ff6100a17234a5b7d4a3e470826d830b358a717.jpg@942w_932h_progressive.jpeg',
'https://blog-icoding.ddnsto.com/upload/5045ae78e674c40f0f295fdac12b6a9e7a11cce1.jpg@942w_920h_progressive.jpeg',
];
let lazyImages = [];
function lazyLoad() {
const windowHeight = window.innerHeight;
const scrollTop = window.scrollY;
const documentHeight = document.body.offsetHeight;
const bottomThreshold = 200;
if (windowHeight + scrollTop >= documentHeight - bottomThreshold) {
// Add 100 images
for (let i = 0; i < 100; i++) {
const img = document.createElement('img');
img.dataset.src = imageUrls[Math.floor(Math.random() * imageUrls.length)];
img.alt = `Random Image ${lazyImages.length + 1}`;
img.className = 'lazy-load';
imageContainer.appendChild(img);
lazyImages.push(img);
}
}
lazyImages.forEach(function(img) {
if (img.getBoundingClientRect().top < window.innerHeight) {
img.src = img.dataset.src;
img.classList.remove("lazy-load");
}
});
lazyImages = document.querySelectorAll("img.lazy-load"); // Update the list after removing class
}
window.addEventListener("scroll", lazyLoad);
lazyLoad(); // Initial check on page load
});
</script>
</body>
</html>