What is the lazy loading and how to best use it

Put us to the test
Put us to the test!
Analyze your site
Select the database

In recent times we are often focusing on the issues of technical SEO and, in particular, it is increasingly necessary to have an informed approach to factors related to the performance of site pages, such as the loading speed or the Page Experience complex, which can become crucial to the success of our online project. Today we continue in this wake and we deepen the discussion on lazy loading, one of the most frequently recommended systems in particular to try to increase the speed of service of images: that’s what it is, how it works and how to avoid errors with slow or lazy loading.

What is the lazy loading

Simply put, lazy loading is a technique based on asynchronous resource loading and on downloading scripts on demand, that is only at the time when that portion of the page serves the user or when those resources are actually necessary for the continuation of the application.

In more technical terms, Google defines lazy loading (which can be translated into English as lazy or slow loading) as a UX best practice that involves deferring the loading of non-critical or non-visible content, which are loaded later than the main content.

Specifically, the expression refers to the process of loading elements of a Web page, such as images, videos, and scripts, only when they are about to enter the user’s viewport (the visible portion of the screen), so as to reduce the initial loading time of pages, improve the user experience, and limit resource consumption by the browser. This approach differs from traditional loading, where all elements on a page are loaded at the same time, regardless of their location or when they will be visible to the user.

What is lazy loading for

In theory, we can apply slow loading to all types of scripts, but in practice the lazy loading system finds more frequent use for images or videos: in any case, its ultimate aim is to lighten the weight of all the contents that can make slow the use of the page.

By only caring about the necessary elements, lazy loading reduces the initial page load time, allowing users to access content more quickly and providing a better user experience. Basically, we don’t have to wait for all the images and scripts on the page to load to start interacting with the content because thanks to the lazy instructions, the system automatically loads only the portion of the page that the user really needs at that moment, allowing it to streamline the download speed and optimize viewing time.

This strategy becomes essential to ensure a good use of the page to all users, regardless of the level of connection and the capacity of the network, and in particular to those who browse with mobile devices where loading is generally less fast than desktop devices (and in fact Google has cited lazy loading also talking about the best practices for the mobile-first indexing). In fact, lazy loading also reduces the consumption of resources (network and processing, such as CPU, GPU and memory) by the browser, providing a smoother browsing experience and limiting any connection or performance problems caused by slow connections or less powerful devices.

In this way, users do not suffer excessive slowdowns caused by connection problems and the overall weight of the overall content of the page, but they can view the necessary resources related to the part of the page they are viewing at that time. This can positively influence the relationship between visitor and site by encouraging browsing and interaction with other pages, which can lead to lower bounce rates and increased engagement.

Just to mention a few figures, as the Web has progressively evolved, we have witnessed huge increases in the number and size of resources sent to users: between 2011 and 2019, for example, the average weight of resources increased from ~100KB to ~400KB for desktops and from ~50KB to ~350KB for mobile devices, while image size increased from ~250KB to ~900KB on desktops and from ~100KB to ~850KB on mobile devices.

Why Lazy Loading is useful: the impact on Core Web Vitals

According to Google, lazy loading offers a number of benefits in terms of performance and user experience, and this also has an effect on meeting Core Web Vitals thresholds, as this lazy approach can help improve these crucial metrics.

In particular, there is a close relationship between lazy loading and at least two of the CWV metrics, namely LCP and CLS:

  1. Largest Contentful Paint (LCP): Lazy loading reduces the time to load the largest content item on the page, such as an image or block of text. A faster LCP indicates a better user experience and has a positive impact on SEO performance. Lazy loading improves initial resource loading, thus reducing the time for LCP.
  2. Cumulative Layout Shift (CLS): Lazy loading, if implemented correctly, can help reduce cumulative page layout shift, a visual instability that occurs when elements on a page change position during loading. Predicting the space occupied by lazily loaded content and using the correct width and height attributes can reduce CLS and improve the user experience.

However, it is critical to implement lazy loading properly to avoid any problems with content visibility or indexing: in particular (as we will see in more detail), using well-established methods or native techniques (such as the “loading” attribute) and thoroughly testing the site will ensure that lazy loading is effective in complying with Core Web Vitals and optimizing website SEO performance.

How lazy loading of resources works

But let us then try to understand concretely what lazy loading means and what it implies from a technical point of view.

In summary, lazy loading relies on the use of JavaScript to monitor the position of media elements on a page: when a user scrolls down the page, JavaScript code continuously checks the position of each element relative to the viewport. If the code detects that an element is about to enter the viewport, it triggers the loading of the element and displays it once the process is complete.

Lazy loading can be implemented using JavaScript or specific external libraries. Through JavaScript, you can use the Intersection Observer API, which monitors the position of elements relative to the viewport during navigation. When a monitored element approaches the viewport, it is loaded and displayed.

To implement lazy loading, developers usually add a specific attribute to the resources they wish to lazily load, such as “data-src” instead of “src” for images, and then use JavaScript or a dedicated library to manage the loading of elements at the appropriate time. Modern websites and browsers natively support lazy loading for some resources, such as images, by introducing the HTML “loading” attribute-for example, to enable lazy loading of an image, simply add loading=”lazy” to the <img> tag-but support for this feature varies among different browsers. Just as an example, as of August 2019, Google has integrated native support for lazy loading at the browser level, eliminating the need to write custom code or employ a separate JavaScript library.

What resources to use Lazy Loading for

It is already clear from what has been written that lazy loading is particularly useful for resources that require a lot of data and processing time, and in particular we recommend its implementation to handle:

  • Images – the most common resource on which lazy loading acts, especially on sites with many high-quality images or in product galleries and catalogs.
  • Embedded videos and iframes, greatly reducing the loading time of pages with multimedia content.
  • Scripts and forms. For sites that use many external scripts or add-on modules, it might be useful to apply lazy loading to these resources to reduce the impact on loading time.

Proper application of the technique allows us to greatly improve site performance, provide a faster user experience, and reduce consumption of network and processing resources.

The benefits of lazy loading

As a result, lazy loading has some interesting advantages:

  • It reduces the initial loading time and initial page weight and the use of system resources, all of which have a positive impact on performance.
  • Avoids wasting processing time, battery and other system resources. After downloading a media resource, the browser must decode it and render its content in the viewport.
  • Makes initialization of the application faster.
  • Allows you to prioritize the main content and upload only when appropriate non-critical resources.
  • It reduces the overall bandwidth load, as it only downloads the scripts, resources and Javascript needed at that time.
  • It reduces the waste of data, as it allows you to use all the bandwidth to download only the resources that are actually displayed by the user.
  • It offers the ability to create a custom Javascript to be put on stand-by and download only as a result of specific user behaviors and interactions.
  • It allows to download scripts from any domain, even different from the current one, and therefore to bypass the “same-domain policy”.

How to implement lazy loading on pages

And so we come to the guide to implementing lazy loading on the site, which requires the use of JavaScript or an appropriate external library that handles the resource loading process.

Below we illustrate an example of how to implement lazy loading using “vanilla” JavaScript and the use of the Intersection Observer API, and next we will look at how to exploit the “loading” attribute in HTML.

  • Implementing Lazy Loading with JavaScript

Using the Intersection Observer API, we can create a JavaScript script to handle lazy loading on the site. Here is an example of how to implement it:

  1. Modify the HTML markup of the resources we intend to load lazily. For images, for example, replace the “src” attribute with “data-src” and add a specific class such as “lazy”: <img data-src=”image.jpg” class=”lazy” alt=”Image example” />
  2. Add the following JavaScript script to the page or JS file:

Codice per implementazione del Lazy Loading con JavaScript

With this code, images will load only when they enter the user’s viewport. The Intersection Observer API is supported in most modern browsers; however, the fallback code ensures that images are still loaded in browsers that do not offer such support.

  • Implementing Lazy Loading with the “loading” attribute

An alternative and simpler method of implementing lazy loading, available in some modern browsers (such as Google Chrome and Microsoft Edge), is to use the “loading” attribute in HTML:

Esempio di codice per implementare Lazy Loading con l'attributo "loading"

Simply add loading=”lazy” to the resources we intend to load lazily and the browser will take care of the rest. However, since support for the “loading” attribute varies among browsers, we recommend using this method in conjunction with a JavaScript implementation to ensure broader coverage.

Lazy loading of the images

The field of action where lazy loading is most frequently found is the loading of videos and images, which are as we know often very heavy resources, that can help generate blocking points in the rendering phase – as well as being increasingly relevant to user engagement.

Thanks to the “energy saving” guaranteed by lazy loading – as we already wrote talking about the tips to optimize the images for SEO – the user immediately sees the resources present in the section of page that is consulting, while everything that is off-screen is loaded only when it actually scrolls the page or performs an action and reaches that portion of content.

Examples of lazy loading

Going back to the definition given by Google, lazy loading allows you to postpone the loading of non-critical content: in reference to images, this adjective is often synonymous with “out of field” and it is precisely in this sense that in the vast majority of cases this technique is used.

In the classic example of slow loading in action, the user reaches a page and starts scrolling as he reads the content; in this process a placeholder image appears (placeholder), which in a few moments is replaced by the final image.

This technique is very useful especially for e-Commerce, because it allows you not to have to load at the same time all the products of the page, which are often hundreds or even more, but to start downloading such resources only following the request of the user, therefore making the page lighter and above all faster.

How to implement lazy loading for images

From a technical point of view, there are at least three ways to implement lazy loading on the pages of the site, which require basic skills on programming languages; alternatively, you can use as we said a Javascript library among the countless available or specific plugins on WordPress, with which to customize various loading parameters to reach the goal of postponing the download of the resource only in conjunction with the scroll or user action.

On modern browsers that implement native slow loading, enabling is using the loading attribute on images and iframes.

Those who know how to manipulate the code can work on HTML, Javascript and CSS: from his blog, Marmonti explains three basic methods, simple and light that require the writing of very few lines of code.

It starts on HTML, using a “little trick” to postpone loading: that is, use the attribute data-src instead of the classic src, so that the browser – not finding the path of the image – temporarily ignores loading

We can also use a jQuery-based script, which replaces the data-src attribute for all images with src to allow the browser to load and display images:

$(document).ready(function() {
[].forEach.call(document.querySelectorAll('img[data-src]'), function(img) {
img.setAttribute('src', img.getAttribute('data-src'));
img.onload = function() {
img.removeAttribute('data-src');
};
});
});

Finally, we can add specific properties to the CSS to produce an appearance effect (fade in) of the images and prevent them from appearing immediately:

img {
opacity: 1;
transition: opacity 0.3s;
}
img[data-src] {
opacity: 0;
}

Lazy Loading and SEO Performance

Ultimately, then, lazy loading is a performance optimization practice that can have a significant impact on both the user experience and the SEO ranking of a site, proving useful in that it can affect the performance and organic visibility of pages.

It should go without saying by now, but page speed is an important factor in algorithmic evaluation and the broader user experience: by its very nature, lazy loading allows for shorter page load times, leading to higher speed scores in performance analysis tools such as Google PageSpeed Insights and Lighthouse.

We have also already mentioned the direct relationship between lazy loading and Core Web Vitals, with a positive influence on passing essential metrics for user experience evaluation and ranking determination. For example, lazy loading reduces the time for Largest Contentful Paint (LCP) and can help reduce Cumulative Layout Shift (CLS) if content is loaded correctly.

In addition, properly implementing lazy loading for images or other multimedia elements can help ensure that these resources are indexed correctly by search engines, thereby improving indexing and potentially even site ranking.

The limitations and critical issues

In the face of so many advantages and practical effects, in fact, there are nevertheless some caveats with respect to the use of this technique because-if we make mistakes-we risk causing a negative impact on the indexing of content and the visibility of resources published on pages.

The general advice is to use well-established libraries or native techniques (such as the “loading” attribute) and carefully test the site to verify that lazy loading works properly and can actually benefit the site’s performance, also from an SEO perspective.

In particular, then, we must pay attention to browser support, adopting when possible implementation methods that are compatible with most browsers and provide alternative solutions in case of less performing or outdated browsers.

For its part, Google explained that Googlebot is capable of scanning, indexing and ranking web pages correctly where lazy loading is implemented correctly, but otherwise we may inadvertently hide content from the search engine, because in the presence of errors the crawler may not be able to view the content and thus process it properly.

It follows, then, that it may be best to avoid lazy loading of main content by tying it to user interactions (such as scrolling, clicking, or typing), because Googlebot will not activate these commands and thus the resources cannot be parsed.

Techniques to correct the content loaded through lazy loading

The Mountain View team then described in a specific guide the three steps to verify to use lazy loading correctly and avoid errors and problems.

First, we need to check that the lazy loading implementation loads all relevant content whenever it is visible in the viewport area, testing the actual functionality of this activation. Examples mentioned include Native Slow Loading for images and iframes, IntersectionObserver and polyfill APIs, and JavaScript library that supports loading data when it enters the viewport area.

In addition, we need to verify that the page supports split loading for infinite scroll, which is important for both users and Google.

On the user side, in fact, continuous scrolling allows users to share and interact with content; for Google, it shows a link to a specific point in the content, rather than to the top of a continuously scrolling page. Best practice is to provide a unique link to each section that users can share and upload directly, and to use History API to update the URL when content is dynamically uploaded.

No less important is the testing phase of the implementations made, so that we can be sure that they actually work: Google suggests using a Puppeteer script (a Node.js library for Chrome headless control) to test the intervention locally; after running the script, we will manually examine the screenshots images created to make sure they contain all the content we expect to be visible and indexed by Google.

An alternative is the URL Inspection tool in Search Console to see if all the images have been loaded. Check the screenshot and the rendered HTML to make sure the images are loaded.

A valid technique to use carefully

In conclusion, lazy loading is really a very advantageous technique that allows you to greatly reduce the initial loading time and payloads of pages on the site, especially in the presence of images and videos in areas not immediately visible.

With this system, users will not have to support unnecessary network activities and multimedia resource processing costs that they may actually never see, but they can still view those resources if they wish and if they reach the given page portion.

And so, especially for sites that have lots of images to upload, lazy loading is a perfect way to reduce unnecessary uploads, as long as you do not block any resource!

Iscriviti alla newsletter

Try SEOZoom

7 days for FREE

Discover now all the SEOZoom features!
TOP