I am working on a project using Vite and trying to implement lazy loading for images. I have the following HTML structure for my images:
html
<img
class="lazy"
src="./src/images/lazy/note.webp"
data-src="./src/images/note.webp"
alt="Image of a book"
class="bookImage"
/>
after build the html looks like this
<img
class="lazy"
src="/assets/note-BK5rAaOe.webp"
data-src="./src/images/note.webp"
alt="Image of a book"
class="bookImage"
/>
Problem:
The issue I am facing is that during the Vite build, the data-src attributes for my images are not being processed. As a result, lazy loading does not work as expected as the location is wrong
To achieve lazy loading, I’m using the following JavaScript:
document.addEventListener('DOMContentLoaded', function () {
const lazyImages = document.querySelectorAll('.lazy');
const lazyLoad = (entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.add('loaded'); // Add loaded class for the animation
observer.unobserve(img); // Stop observing the image once it's loaded
}
});
};
const observer = new IntersectionObserver(lazyLoad, {
root: null,
rootMargin: '0px',
threshold: 0.1,
});
lazyImages.forEach(img => observer.observe(img));
});
Additionally, here is my vite.config.js file:
import { defineConfig } from 'vite';
export default defineConfig({
css: {
preprocessorOptions: {
scss: {
// Use the modern API
api: 'modern-compiler', // or "modern"
},
},
},
});
How can I configure Vite to compile the data-src attributes properly?
Do I need to manually add images to achieve lazy loading, or is there a way to automate this process?
I also tried building the same setup using Parcel, but I encountered the same issue with the data-src attributes not being compiled.
Any guidance or suggestions on how to resolve this issue would be greatly appreciated!