From aa1d74f3cb822cd0b6dfeed489af4554dbce55a6 Mon Sep 17 00:00:00 2001 From: George Birikorang Date: Fri, 19 Sep 2025 09:54:06 -0700 Subject: [PATCH] feat: implement lazy loading for product images to enhance performance - Added CSS styles for lazy loading images, improving initial load times and user experience. - Updated ProductManager class to initialize lazy loading functionality, utilizing Intersection Observer for efficient image loading as they come into view. - Modified image elements in product catalog to support lazy loading with appropriate data attributes. --- product-catalog.html | 10 +++++++++ scripts/products.js | 52 +++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/product-catalog.html b/product-catalog.html index c8e9091..d76971c 100644 --- a/product-catalog.html +++ b/product-catalog.html @@ -15,6 +15,16 @@ display: flex !important; } } + + /* Lazy loading styles */ + .lazy-load { + opacity: 0.7; + transition: opacity 0.3s ease-in-out; + } + + .lazy-load.loaded { + opacity: 1; + } { addImageEnlargementListeners(); + this.initLazyLoading(); }, 50); } @@ -143,10 +144,12 @@ class ProductManager { }">
${product.alt}
@@ -441,6 +444,49 @@ class ProductManager { this.updateFilterButtonText(); }); } + + // Initialize lazy loading + this.initLazyLoading(); + } + + // Initialize lazy loading for images + initLazyLoading() { + // Use Intersection Observer for better performance + if ("IntersectionObserver" in window) { + const imageObserver = new IntersectionObserver( + (entries, observer) => { + entries.forEach((entry) => { + if (entry.isIntersecting) { + const img = entry.target; + if (img.dataset.src) { + img.src = img.dataset.src; + img.classList.remove("lazy-load"); + img.classList.add("loaded"); + observer.unobserve(img); + } + } + }); + }, + { + rootMargin: "50px 0px", // Start loading 50px before image comes into view + threshold: 0.01, + } + ); + + // Observe all lazy-loaded images + const lazyImages = document.querySelectorAll(".lazy-load"); + lazyImages.forEach((img) => imageObserver.observe(img)); + } else { + // Fallback for older browsers - load all images immediately + const lazyImages = document.querySelectorAll(".lazy-load"); + lazyImages.forEach((img) => { + if (img.dataset.src) { + img.src = img.dataset.src; + img.classList.remove("lazy-load"); + img.classList.add("loaded"); + } + }); + } } // Update results count