Lazy loading is a technique used to defer the loading of images and videos on a web page until they are about to enter the user’s viewport (the visible portion of the page). This can significantly improve page load times and reduce unnecessary data transfer. To implement lazy loading, you can use the loading
attribute for images and the loading
attribute and poster
attribute for videos. Here’s an example
Lazy Loading for Images:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lazy Loading Images Example</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<p>Scroll down to see lazy-loaded images.</p>
<img src="placeholder.jpg" alt="Image 1" loading="lazy" data-src="image1.jpg">
<img src="placeholder.jpg" alt="Image 2" loading="lazy" data-src="image2.jpg">
<img src="placeholder.jpg" alt="Image 3" loading="lazy" data-src="image3.jpg">
<script>
// JavaScript to lazy load images
document.addEventListener("DOMContentLoaded", function () {
const lazyImages = document.querySelectorAll('img[loading="lazy"]');
lazyImages.forEach((img) => {
img.src = img.getAttribute("data-src");
img.removeAttribute("data-src");
});
});
</script>
</body>
</html>
In this example, the loading="lazy"
attribute is added to each img
element, indicating that the browser should lazily load the images. A data-src
attribute is used to store the actual image source. The JavaScript code at the end of the document listens for the DOMContentLoaded
event and swaps out the src
attribute with the data-src
attribute when it’s time to load the images.