Skip to content

Instantly share code, notes, and snippets.

@fzn0x
Created February 16, 2024 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fzn0x/269a271e82d8c7946139fcb720aa0c13 to your computer and use it in GitHub Desktop.
Save fzn0x/269a271e82d8c7946139fcb720aa0c13 to your computer and use it in GitHub Desktop.
Lazy Asset Loading - fzn0x
<!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