
Here’s a simple script for lazy loading images on a website using JavaScript. This approach will improve page load performance by only loading images when they are in the viewport.
HTML Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lazy Load Images</title> <style> .lazy { display: block; width: 100%; /* Adjust as necessary */ height: auto; /* Maintain aspect ratio */ background: #f0f0f0; /* Placeholder color */ } </style> </head> <body> <h1>Lazy Loading Images Example</h1> <img class="lazy" data-src="image1.jpg" alt="Image 1" /> <img class="lazy" data-src="image2.jpg" alt="Image 2" /> <img class="lazy" data-src="image3.jpg" alt="Image 3" /> <img class="lazy" data-src="image4.jpg" alt="Image 4" /> <img class="lazy" data-src="image5.jpg" alt="Image 5" /> <script src="lazyload.js"></script> </body> </html>
JavaScript (lazyload.js)
document.addEventListener("DOMContentLoaded", function() { const lazyImages = document.querySelectorAll('img.lazy'); const observerOptions = { root: null, // Use the viewport as the root rootMargin: '0px', threshold: 0.1 // Trigger when 10% of the image is in view }; const imageObserver = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { const img = entry.target; // Replace the placeholder with the actual image img.src = img.dataset.src; img.classList.remove('lazy'); // Stop observing the image after it's loaded observer.unobserve(img); } }); }, observerOptions); lazyImages.forEach(image => { imageObserver.observe(image); }); });
Explanation
- HTML Structure: Each image uses the class
lazy
and adata-src
attribute to hold the actual image URL. This tells the script not to load the image until it is visible. - CSS Styles: Use basic styles to give a placeholder appearance for images that are being lazy-loaded.
- JavaScript Logic:
- The script waits for the DOM to load before executing.
- It selects all images with the class
lazy
. - An
IntersectionObserver
is created to watch when the images enter the viewport. - When an image is intersected, the script sets its
src
attribute to the value indata-src
, causing the image to load. - After loading, the script removes the
lazy
class and stops observing that image.
Usage
Make sure to link the lazyload.js
script in your HTML document. You can adjust the threshold
and rootMargin
based on your needs to control when the images start loading as they come into view.
This setup ensures a more efficient loading process, especially for pages with many images.