Image Lazy-loading for the website using HTML attribute and Javascript

Himalaya Pagada
2 min readJul 26, 2021
image lazy-loading using html, css and javascript by himalaya

HTML attribute to lazy-load the images without any custom lazy-loading code or any third-party javascript library. Please go through the details below:

Html loading attribute

You can use the loading attribute of HTML to completely delay the loading of offscreen images that can be reached by scrolling:

<img src="image.png" loading="lazy" alt="…" width="200" height="200">"

“loading” attributes:
1) auto: Default lazy-loading behavior of the browser.
2) lazy: Defer loading of the images until it reaches the viewport from a calculated distance.
3) eager: Load the resource immediately, regardless of where it’s located on the document.

Browser compatibility

For most websites, adding this attribute to inline images will be a performance boost and save users loading images. If the browser does not support lazy-loading then the attribute will be ignored and images will load immediately, as normal.

Check the details of browser support below:

browser wise lazy-loading support

Lazy-loading for CSS background-image

<img> tags are the most common way of displaying images on web pages, images can also be displayed via the CSS background-image property.
HTML lazy-loading does not apply to CSS background images, so you need to use javascript methods if you have background images to lazy-load.

Example

in HTML

<div class=”lazy-bg img1"></div>
<div class=”lazy-bg img2"></div>
<div class=”lazy-bg img3"></div>

in CSS

.lazy-bg {width: 100%;height: 800px;background-color: #ccc;} 
.img1.visible {background: url(../imgs/lazy-1.jpg) no-repeat;background-size: cover;}
.img2.visible {background: url(../imgs/lazy-2.jpg) no-repeat;background-size: cover;}
.img3.visible {background: url(../imgs/lazy-3.jpg) no-repeat;background-size: cover;}

In Javascript

document.addEventListener(“DOMContentLoaded”, function () {
var lazyBackgrounds = [].slice.call(document.querySelectorAll(“.lazy-bg”));
if (“IntersectionObserver” in window && “IntersectionObserverEntry” in window && “intersectionRatio” in window.IntersectionObserverEntry.prototype) {
let lazyBackgroundObserver = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
entry.target.classList.add(“visible”);
lazyBackgroundObserver.unobserve(entry.target);
}
});
});
lazyBackgrounds.forEach(function (lazyBackground) {
lazyBackgroundObserver.observe(lazyBackground);
});
}
});

--

--