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); }); });
lazy
and a data-src
attribute to hold the actual image URL. This tells the script not to load the image until it is visible.lazy
.IntersectionObserver
is created to watch when the images enter the viewport.src
attribute to the value in data-src
, causing the image to load.lazy
class and stops observing that image.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.
WordPress development has evolved significantly, and modern tooling plays a crucial role in creating efficient…
I. Project Overview The goal is to automate the process of notifying search engines (like…
1. Database Structure (MySQL) We'll need a database table to store information about our website's…
This explanation aims to provide a solid foundation for understanding the process and implementing your…
Okay, here's a comprehensive guide on building a real-time website chat script using PHP, HTML,…
Comprehensive guide on creating a simple website analytics system using PHP, HTML, CSS, JavaScript, and…