Certainly! Here are code examples for lazy loading and infinite scroll:
- Lazy Loading (Image Lazy Loading):
```html
2. Infinite Scroll:
```html
<!-- HTML -->
<div id="content">
<!-- Initial content -->
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<!-- Loader element -->
<div id="loader">Loading...</div>
</div>
<!-- JavaScript -->
<script>
window.addEventListener('DOMContentLoaded', function() {
var content = document.getElementById('content');
var loader = document.getElementById('loader');
var page = 1;
function loadMoreItems() {
loader.style.display = 'block'; // Show loader
// Simulating an API call or fetching more data
setTimeout(function() {
// Append new items
var items = '';
for (var i = 1; i <= 3; i++) {
items += '<div class="item">Item ' + (page * 3 + i) + '</div>';
}
content.innerHTML += items;
loader.style.display = 'none'; // Hide loader
page++; // Increment page number
}, 1000);
}
function handleScroll() {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
var windowHeight = window.innerHeight || document.documentElement.clientHeight;
var contentHeight = content.offsetHeight;
if (scrollTop + windowHeight >= contentHeight) {
loadMoreItems();
}
}
window.addEventListener('scroll', handleScroll);
});
</script>
These code examples demonstrate the basic implementation of lazy loading images and implementing infinite scroll functionality. Remember to adapt the code to your specific use case and requirements.