The Main Culprit of Web Application Performance Degradation and the Necessity of Lazy Loading
In modern web applications, images are one of the key elements that influence user experience (UX) and web performance. With the increasing use of high-resolution images, the proportion of image content on pages has risen, making slow website loading speeds an unavoidable problem. Loading all images at once during the initial loading phase causes critical performance bottlenecks like the following:
-
Increased Initial Loading Time (Delays in FCP and LCP): By downloading images outside of the viewport, the time it takes for users to actually see content (First Contentful Paint) and the time at which the largest content element is loaded (Largest Contentful Paint) are significantly delayed. This negatively impacts the Core Web Vitals metrics as well.
-
Unnecessary Bandwidth Consumption: Network resources are wasted for images that users will not scroll to view, increasing the burden of data charges in mobile environments and hindering the loading of other important resources in desktop environments due to unnecessary network requests.
-
Increased Server Load: Requests for all images occurring simultaneously put excessive load on the server, which can lead to reduced service reliability.
One of the most effective strategies to resolve these issues is image lazy loading. Lazy loading is a technique that loads images asynchronously when they enter the user's viewport or reach a specific threshold, instead of loading all of them during the initial loading phase of a web page.
How Image Lazy Loading Works and How to Apply It
There are primarily two major ways to implement lazy loading, and it is necessary to understand their pros and cons to select according to the project's requirements.
1. Browser Native Lazy Loading (loading="lazy"
)
This is the simplest yet powerful method that can be implemented by merely adding the loading="lazy"
attribute to the HTML <img>
tag. It is supported by most modern browsers, which handle lazy loading in an optimized manner.
<img src="placeholder.jpg"
data-src="actual-image.jpg"
alt="Description of image"
loading="lazy"
width="500"
height="300">
-
Advantages:
-
Ease of Implementation: It can be applied with just the addition of an HTML attribute without any separate JavaScript code.
-
Performance Optimization: Since it is implemented at the browser engine level, it can operate more efficiently and quickly than JavaScript-based solutions.
-
Reduces Developer Burden: The browser takes care of it without complex Intersection Observer API or event listener management.
-
-
Disadvantages:
-
Browser Support: It may not be perfectly supported in all legacy browsers. (However, most modern browsers do support it.)
-
Lack of Detailed Control: Developers find it difficult to meticulously control loading thresholds or strategies.
-
Recommendation: Unless there are specific control requirements, it is advisable to prioritize applying Native Lazy Loading.
2. JavaScript-based Lazy Loading (Using Intersection Observer API)
When more detailed control is needed or a fallback is required for browsers that do not support the loading="lazy"
attribute, JavaScript-based lazy loading can be implemented. In the past, the method mainly used scroll event listeners, but due to performance issues, the Intersection Observer API has become the standard.
Basic Implementation Logic:
-
Initially, specify a Placeholder image in the image's
src
attribute or store the actual image URL in thedata-src
attribute. -
Create an Intersection Observer instance and observe the image elements.
-
When the image element enters the viewport or reaches the defined threshold, the observer's callback function is executed.
-
Within the callback function, move the actual image URL stored in
data-src
to thesrc
attribute to load the image. -
Once the image loading is complete, cease observation of that image element.
// HTML (example)
// <img class="lazyload" data-src="actual-image.jpg" alt="Description">
// JavaScript
document.addEventListener("DOMContentLoaded", function() {
const lazyImages = [].slice.call(document.querySelectorAll("img.lazyload"));
if ("IntersectionObserver" in window) {
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
// lazyImage.srcset = lazyImage.dataset.srcset; // if srcset is needed
lazyImage.classList.remove("lazyload");
lazyImageObserver.unobserve(lazyImage);
}
});
}, {
// Root Margin: area to preload images from the viewport edges (px or %)
// E.g.: "0px 0px 200px 0px" preloads 200px towards the bottom
rootMargin: "0px 0px 200px 0px"
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
} else {
// Fallback for browsers that do not support IntersectionObserver
// (e.g., using scroll event listener or loading all images immediately)
// This part is not recommended for performance, so assess considering the main target browsers
lazyImages.forEach(function(lazyImage) {
lazyImage.src = lazyImage.dataset.src;
});
}
});
-
Popular JavaScript Lazy Loading Libraries:
-
lazysizes: Very lightweight, SEO-friendly, and supports various image formats, including
srcset
andpicture
elements. It can also serve as a fallback for Native Lazy Loading. -
lozad.js: Known for its small bundle size and high performance.
-
Considerations and Optimization Tips When Implementing Lazy Loading
While lazy loading is a powerful performance optimization technique, indiscriminate application to all images can negatively impact user experience.
- Managing 'Above the Fold' Images: Lazy loading should not be applied to images that are immediately visible on the initial screen (Above the Fold). These images directly impact the Largest Contentful Paint (LCP) of the page, so they should be explicitly designated with
loading="eager"
or excluded from lazy loading for immediate loading.
<img src="logo.png" alt="Company Logo" width="100" height="50" loading="eager">
-
Specify
width
andheight
Attributes: Thewidth
andheight
attributes of images should be explicitly provided in HTML to prevent Cumulative Layout Shift (CLS). This allows the browser to reserve space for the image beforehand, preventing layout shifts during loading, which is crucial for improving Core Web Vitals scores. -
Use Placeholder Images: It is advisable to use blurred low-resolution images or solid-color background placeholders until lazy-loaded images are loaded to minimize visual empty spaces for users. This communicates to users that the page is in the process of loading.
-
Utilize
srcset
and<picture>
Tag: Using responsive images (srcset
) and art direction (picture
tag) in conjunction with lazy loading can provide optimized images for different screen sizes and resolutions, further reducing unnecessary image downloads.
<picture>
<source srcset="image-large.webp" type="image/webp" media="(min-width: 1200px)" loading="lazy">
<source srcset="image-medium.webp" type="image/webp" media="(min-width: 768px)" loading="lazy">
<img src="placeholder.jpg" data-src="image-small.jpg" alt="Description" loading="lazy">
</picture>
Conclusion: Capturing Two Hares with Lazy Loading - Performance and User Experience
Image lazy loading transcends merely delaying image loading; it is an essential web optimization technique that dramatically improves the initial loading performance of web pages, optimizes bandwidth usage, and reduces server load. As the importance of web performance metrics like Core Web Vitals increases, the strategic application of lazy loading has become a necessity that developers must consider.
It is advisable to prioritize Native Lazy Loading, but if detailed control is necessary or specific browser environments need to be supported, consider implementing JavaScript-based solutions using the Intersection Observer API or utilizing libraries. Also, by applying optimization tips such as managing 'Above the Fold' images, specifying width
/height
, and using placeholders, you can provide users with a fast and pleasant web experience.
There are no comments.