Lazy Loading for Faster Websites JavaScript, HTML
👤 Sharing: AI
```javascript
// JavaScript - Lazy Loading Implementation
// Function to check if an element is in the viewport
function isInViewport(element) {
const rect = element.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
// Function to load an image
function loadImage(image) {
const src = image.dataset.src; // Get the data-src attribute
if (src) {
image.src = src;
image.removeAttribute('data-src'); // Optional: Remove the data-src attribute after loading
image.classList.add('loaded'); // Optional: Add a class to indicate loaded images
// Optional: Lazy load background images
const bgSrc = image.dataset.bg;
if (bgSrc) {
image.style.backgroundImage = `url(${bgSrc})`;
image.removeAttribute('data-bg');
}
}
}
// Function to handle lazy loading
function lazyLoad() {
const lazyImages = document.querySelectorAll('img[data-src], .lazy-background[data-bg]'); // Target both image and background lazy loading
lazyImages.forEach(image => {
if (isInViewport(image)) {
loadImage(image);
}
});
// If all lazy images are loaded, stop listening to scroll events (optional)
if (document.querySelectorAll('img[data-src], .lazy-background[data-bg]').length === 0) {
document.removeEventListener('scroll', lazyLoad);
window.removeEventListener('resize', lazyLoad); // Remove resize listener as well
}
}
// Event listeners for scroll and resize events
document.addEventListener('scroll', lazyLoad);
window.addEventListener('resize', lazyLoad);
// Initial lazy load on page load (important for images already in viewport)
document.addEventListener('DOMContentLoaded', lazyLoad);
// HTML - Example usage
/*
<!DOCTYPE html>
<html>
<head>
<title>Lazy Loading Example</title>
<style>
/* Optional styling * /
img {
display: block;
margin-bottom: 20px;
width: 100%; /* Ensure images take up space * /
height: auto;
opacity: 0; /* Initially hide the image * /
transition: opacity 0.5s ease; /* Smooth transition * /
}
img.loaded {
opacity: 1; /* Show image when loaded * /
}
.placeholder {
background-color: #eee; /* Gray placeholder * /
width: 100%;
height: 200px; /* Adjust height as needed * /
margin-bottom: 20px;
}
.lazy-background {
width: 100%;
height: 300px;
background-color: #ddd; /* Placeholder background color */
background-size: cover; /* Ensure background image covers the element */
background-position: center;
opacity: 0; /* Hide initially */
transition: opacity 0.5s ease;
}
.lazy-background.loaded {
opacity: 1; /* Show when loaded */
}
</style>
</head>
<body>
<h1>Lazy Loading Example</h1>
<div class="placeholder">Placeholder for above image</div>
<img data-src="https://via.placeholder.com/600x400/456789/fff?text=Image+1" alt="Image 1" width="600" height="400">
<div class="placeholder">Placeholder for above image</div>
<img data-src="https://via.placeholder.com/600x400/987654/fff?text=Image+2" alt="Image 2" width="600" height="400">
<div class="placeholder">Placeholder for above image</div>
<img data-src="https://via.placeholder.com/600x400/abcdef/fff?text=Image+3" alt="Image 3" width="600" height="400">
<div class="placeholder">Placeholder for background image</div>
<div class="lazy-background" data-bg="https://via.placeholder.com/800x400/fedcba/000?text=Background+Image+1"></div>
<div class="placeholder">Placeholder for background image</div>
<div class="lazy-background" data-bg="https://via.placeholder.com/800x400/aabbcc/fff?text=Background+Image+2"></div>
<script>
// JavaScript code from above goes here
// (or include it from an external .js file)
</script>
</body>
</html>
*/
```
👁️ Viewed: 9
Comments