To implement lazy loading of images and content using JavaScript, you can follow these steps:
Identify the images and content that you want to lazy load by assigning a specific class or data attribute to them (e.g., "lazy-load").
Initially, set the source of all those images to a placeholder image (a small, transparent GIF, or a low-resolution version of the image) that loads quickly. Set the content to a placeholder text if needed.
Add an event listener to the "DOMContentLoaded" or "load" event of the window (or any other suitable event) to detect when the page finishes loading or when the user scrolls.
Inside the event listener, loop through all the elements with the "lazy-load" class or data attribute. Check if each element is within the visible viewport.
getBoundingClientRect
method to get the top, bottom, left, right, width, and height values of an element relative to the viewport. Compare these values with the window's inner height and inner width to check if the element is visible.If an element is visible, replace the source of the image or load the content dynamically.
To replace the source of an image, assign the actual source URL to the src
attribute of the image.
To load content dynamically (e.g., from a separate file or via AJAX), use the innerHTML
property of the element and assign the fetched content to it.
Remove the "lazy-load" class or data attribute from the element to prevent unnecessary rechecking.
Here's a sample implementation using JavaScript:
document.addEventListener("DOMContentLoaded", function() {
var lazyElements = document.querySelectorAll(".lazy-load");
function isElementInViewport(elem) {
var bounding = elem.getBoundingClientRect();
return (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
function lazyLoad() {
for (var i = 0; i < lazyElements.length; i++) {
if (isElementInViewport(lazyElements[i])) {
if (lazyElements[i].getAttribute("data-src")) {
lazyElements[i].src = lazyElements[i].getAttribute("data-src");
lazyElements[i].removeAttribute("data-src");
}
lazyElements[i].classList.remove("lazy-load");
}
}
}
window.addEventListener("load", lazyLoad);
window.addEventListener("scroll", lazyLoad);
window.addEventListener("resize", lazyLoad);
window.addEventListener("orientationchange", lazyLoad);
});
Remember to update the class or data attribute names and modify the conditions based on your specific requirements.