In today's fast-paced digital world, having a high-performance website is essential. One critical aspect of this is ensuring that your images load efficiently. Users expect a smooth and speedy browsing experience, and this article will show you how to achieve that.
You'll explore the concept of lazy loading images and learn how to implement it using HTML and JavaScript with the Intersection Observer API.
What Is Lazy Loading?
Lazy loading delays the loading of elements, such as images, until required. Instead of loading all images when a page loads, lazy loading only loads the images that are currently visible or near the user's viewing area. This improvement in website performance decreases the initial load time and conserves bandwidth.
Why Use Lazy Loading?
There are several compelling reasons to use lazy loading of images on your website, such as:
- Faster Initial Page Load: Lazy loading prevents all images from loading at once, reducing the initial page load time. Users can start interacting with your site sooner, leading to a better user experience.
- Improved Page Responsiveness: By loading images as users scroll, the website remains responsive and fluid, ensuring smooth scrolling and navigation without the need to wait for all content to load.
- Bandwidth Savings: Lazy loading conserves bandwidth, making it ideal for mobile users and those on slow internet connections. This can reduce your website's data consumption, benefiting the users.
- SEO Benefits: Search engines like Google consider page speed as a ranking factor. Lazy loading can positively impact your site's SEO performance by improving loading time.
Now that you understand why lazy loading is beneficial, let's explore how to implement it.
Implementing Lazy Loading: The HTML Markup
To get started, you'll need to modify your HTML code to include the loading="lazy" attribute on your <img> tags.
<body>
<main>
<section>
<img src="./image-one-high.jpg" alt="" loading="lazy" />
</section>
<section>
<img src="./image-two-high.jpg" alt="" loading="lazy" />
</section>
<section>
<img src="./image-three-high.jpg" alt="" loading="lazy" />
</section>
</main>
</body>
The loading attribute is used in HTML to control the loading behavior of elements on a web page. When you set loading="lazy" on a <img> tag, it tells the browser to defer the loading of the resource until it is needed.
At the moment, the page looks like this:
Implementing Lazy Loading: The JavaScript Implementation
To take your lazy loading to the next level, use the Intersection Observer API. This API lets you watch when an element comes into or goes out of the viewport.
The rationale behind employing the Intersection Observer for lazy loading images is simple: when the page loads, it fetches a lower-quality image.
Then, as this image becomes visible within the viewport, JavaScript swaps it out for the higher-quality version. To put this into practice, modify your HTML.
<section>
<img
<!-- Low-quality image as a placeholder -->
src="./image-one-low.webp"
alt=""
loading="lazy"
<!-- High-quality image stored in the data attribute -->
data-src="./image-one-high.jpg"
/>
</section>
<section>
<img
<!-- Low-quality image as a placeholder -->
src="./image-two-low.webp"
alt=""
loading="lazy"
<!-- High-quality image stored in the data attribute -->
data-src="./image-two-high.jpg"
/>
</section>
<section>
<img
<!-- Low-quality image as a placeholder -->
src="./image-three-low.webp"
alt=""
loading="lazy"
<!-- High-quality image stored in the data attribute -->
data-src="./image-three-high.jpg"
/>
</section>
Here, the primary image source is the low-quality version and the high-quality image is the secondary source. The page then looks like this:
Next, select all the images you wish to lazy-load:
"use strict";
const lazyImages = document.querySelectorAll('img[loading="lazy"]');
After that, create an IntersectionObserver object.
const observer = new IntersectionObserver();
Then pass in the entries (an array of IntersectionObserverEntry objects, representing the elements being observed and their intersection with the viewport) and observer (the IntersectionObserver instance itself).
const observer = new IntersectionObserver((lazyImages, observer) => { });
Next, check for intersections and swap the low-quality image for the high-quality one whenever that element intersects.
const observer = new IntersectionObserver((lazyImages, observer) => {
lazyImages.forEach((image) => {
if (image.isIntersecting) {
const lazyImage = image.target;
lazyImage.src = lazyImage.dataset.src; // Swap the image source
observer.unobserve(lazyImage); // Stop observing this image
}
});
});
Finally, initialize observation for each element.
// Start observing each lazy image
lazyImages.forEach((lazyImage) => { observer.observe(lazyImage); });
And with that, you’ve implemented lazy loading with JavaScript.
Lazy Loading Considerations
When integrating lazy loading, it becomes vital to consider the following aspects:
- Accessibility: To ensure accessibility, provide alternative text for images with the alt attribute. This information serves as a reliance point for screen readers.
- Browser Compatibility: Before the implementation of lazy loading, confirm its compatibility with different browsers. Not all browsers extend support for this feature. In certain instances, the inclusion of a polyfill may become imperative, especially for older browsers. A tool like CanIUse is a valuable resource for evaluating browser compatibility.
- Testing: The comprehensive testing of the lazy loading implementation across a spectrum of devices and screen dimensions assumes paramount importance.
Enhancing Website Speed and User Experience
When you incorporate lazy loading for images on your website, you can speed up your site and improve the user experience. Faster loading time and smoother browsing experiences are what users want, and this technique delivers the same.
Plus, you'll enjoy better SEO and save on bandwidth usage. So, why wait? Start optimizing your website today with this straightforward yet powerful method.