Make sure your <img />
tags have the src
and a data-src
arttributes set to image source url as shown in
the example below:
Note : You can have an alernative paceholder image say for user avatar display photo or just as shown below using the same image to be lazy-loaded.
<img src="./images/logo/jengalogohorizontal.png" data-src="./images/logo/jengalogohorizontal.png" alt="loading image.." />
Create an empty lazyLoad.js
in your project and copy the code snippet provided here.
Copy the code snippet below to your lazyLoad.js
and save.
let imagesToLoad = document.querySelectorAll('img[data-src]');
let loadImages = (image) => {
image.setAttribute('src', image.getAttribute('data-src'));
image.onload = () => {
image.removeAttribute('data-src');
};
};
if ('IntersectionObserver' in window) {
let observer = new IntersectionObserver((items, observer) => {
items.forEach((item) => {
if (item.isIntersecting) {
loadImages(item.target);
observer.unobserve(item.target);
}
});
});
imagesToLoad.forEach((img) => {
observer.observe(img);
});
}
else {
imagesToLoad.forEach((img) => {
loadImages(img);
});
}
To your page's main styles copy the following code snippet to it to style up the loading...
img[data-src] {
filter: blur(0.2em);
}
img {
filter: blur(0em);
transition: filter 0.5s;
}