Created
February 16, 2024 16:29
-
-
Save fzn0x/269a271e82d8c7946139fcb720aa0c13 to your computer and use it in GitHub Desktop.
Lazy Asset Loading - fzn0x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Lazy Loading with Infinite Scroll</title> | |
<style> | |
#image-container { | |
column-count: 3; | |
column-gap: 10px; | |
margin: 20px; | |
} | |
.image-item { | |
break-inside: avoid-column; | |
margin-bottom: 10px; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="image-container"></div> | |
<script> | |
let page = 1; // Initial page | |
const imagesContainer = document.getElementById('image-container'); | |
function fetchImages(page) { | |
// Replace 'your-api-endpoint' with the actual endpoint that returns paginated image data | |
const apiUrl = `https://your-api-endpoint?page=${page}`; | |
fetch(apiUrl) | |
.then(response => response.json()) | |
.then(data => { | |
const images = data.images; | |
images.forEach(image => { | |
const imageElement = document.createElement('img'); | |
imageElement.src = 'placeholder.jpg'; // Use a placeholder image | |
imageElement.setAttribute('data-src', image.url); // Actual image source | |
imageElement.alt = image.alt; | |
imageElement.loading = 'lazy'; | |
const imageItem = document.createElement('div'); | |
imageItem.classList.add('image-item'); | |
imageItem.appendChild(imageElement); | |
imagesContainer.appendChild(imageItem); | |
}); | |
}) | |
.catch(error => console.error('Error fetching images:', error)); | |
} | |
function loadMoreImages() { | |
page++; | |
fetchImages(page); | |
} | |
// Initial load | |
fetchImages(page); | |
// Infinite scroll | |
window.addEventListener('scroll', () => { | |
const scrollHeight = document.documentElement.scrollHeight; | |
const scrollTop = window.scrollY; | |
const clientHeight = window.innerHeight; | |
if (scrollTop + clientHeight >= scrollHeight - 200) { | |
loadMoreImages(); | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment