From fdb26c1d578ba601b86d601191e4623baef2864c Mon Sep 17 00:00:00 2001 From: Shraddha Singh Date: Sat, 1 Jul 2023 14:38:29 +0530 Subject: [PATCH] Lazy loading is added --- assets/style.css | 8 ++++++++ index.html | 5 ++++- script.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 1 deletion(-) diff --git a/assets/style.css b/assets/style.css index 3e702307..e408c0d3 100644 --- a/assets/style.css +++ b/assets/style.css @@ -485,3 +485,11 @@ body { color: #1d0f44ad; transition: all 0.3s ease; } + +.lazy { + opacity: 0; + transition: opacity 0.3s; +} +.loaded { + opacity: 1; +} diff --git a/index.html b/index.html index 43709b0f..2fa90946 100644 --- a/index.html +++ b/index.html @@ -2,6 +2,10 @@ +
+ + + @@ -73,7 +77,6 @@

About Us

-
Projects
diff --git a/script.js b/script.js index 9682d5e6..c992ad2c 100644 --- a/script.js +++ b/script.js @@ -203,3 +203,48 @@ function typeLetter() { } const intervalId = setInterval(typeLetter, 100); + +(function() { + 'use strict'; + + var lazyElements = [].slice.call(document.querySelectorAll('.lazy')); + + var loadLazyContent = function(lazyElement) { + var url = lazyElement.getAttribute('data-src'); + + // Make an AJAX request to fetch the lazy content + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange = function() { + if (xhr.readyState === XMLHttpRequest.DONE) { + if (xhr.status === 200) { + // Set the fetched content as the innerHTML of the lazy element + lazyElement.innerHTML = xhr.responseText; + lazyElement.classList.add('loaded'); + } + } + }; + xhr.open('GET', url, true); + xhr.send(); + }; + + var lazyLoadHandler = function() { + lazyElements.forEach(function(lazyElement) { + var rect = lazyElement.getBoundingClientRect(); + + // Check if the lazy element is within the viewport + if (rect.top >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight)) { + loadLazyContent(lazyElement); + } + }); + + // Remove the event listener once all lazy elements are loaded + if (lazyElements.length === 0) { + window.removeEventListener('scroll', lazyLoadHandler); + } + }; + + // Add the lazyLoadHandler to the scroll event + window.addEventListener('scroll', lazyLoadHandler); + lazyLoadHandler(); // Call it once to load any initially visible elements + })(); + \ No newline at end of file