Home > Web Front-end > JS Tutorial > Learn more about lazy loading in JavaScript

Learn more about lazy loading in JavaScript

青灯夜游
Release: 2020-11-05 17:59:30
forward
2585 people have browsed it

Learn more about lazy loading in JavaScript

In this article, we will look at how lazy loading works on the web. We'll cover the native lazy loading API - how lazy loading is implemented, the importance and advantages of lazy loading, and finally a simple use case for lazy loading web content.

Understanding the lazy loading API and how it works will help developers who are already using libraries and frameworks that implement these techniques understand what is going on under the hood. Additionally, if they plan to implement their own lazy loading library, they will be able to perform more guided research and apply the techniques they learned.

For a real use case, marketing and advertising companies that generate revenue from ads on their platform can easily optimize and apply lazy loading to easily judge which ads are seen by users visiting their platform , thereby making better business decisions.

Recommended tutorial: "JavaScript Video Tutorial"

What is lazy loading?

Based on According to Wikipedia, lazy loading is a design pattern used to delay the initialization of an element or object when needed. This means that only when the user scrolls on the web page, the target DOM element is loaded and visible relative to the parent DOM element (based on a set threshold when there is an intersection between the two elements).

The disadvantages of not adopting this pattern may result in:

  • Due to multiple simultaneous network requests to obtain multiple images or other web resources from one or more sources or Batch requests, causing severe lag in page performance

  • Increased page load time due to size of package to download/fetch

  • User retention Low, mainly suitable for areas with poor Internet connection. When we developers make the mistake of not implementing lazy loading early on, it's not uncommon for users to avoid using the platform entirely

  • due to improper handling of resources or assets such as images, iframes, and videos. Huge impact on web performance and accessibility

Currently, most modern and newer browsers support lazy loading on the web. However, for browsers that don't yet provide this support, shims or libraries that implement this technology provide a simple API layer on top of them.

Lazy loading solves the problem of reducing initial page load time - only showing resources, such as images or other content, that the user needs to see when initializing the web page and subsequently as they scroll the page.

As we all know, web performance and accessibility issues are multifaceted; reducing page size, memory footprint, and general load times can do a lot for the web platform. The advantages of lazy loading become obvious when we have a bunch of images and videos and load them all at once when the browser DOM is initialized.

Of course, you should now understand what this will lead to, as we discussed earlier.

From the data, most websites rely heavily on images and other web content, such as videos or iframes, to deliver information to their target audience. While this may seem trivial and simple, the way we display this content to our users ultimately determines the performance of our platform.

Additionally, actions that help optimize page load times (such as events that rely on whether the user scrolls to a specific part of the page) are some use cases for lazy loading. As this article continues, we'll learn more about other use cases in real-world settings.

Native Lazy Loading API

Lazy loading is built on top of the Intersection Observer API, a browser API that provides a way to detect or know when an element, called the target, parent element, is available or visible within the browser viewport, as the case may be.

When this happens, the handler function is called to help handle other parts of the code logic, which we will see later.

With this new and improved browser API, we can also know when two DOM elements intersect - here meaning, when the target DOM element enters the browser's viewport, or is in contact with the browser's viewport. Intersects another element (most likely its parent).

To better understand how lazy loading works, we first have to understand how to create an intersection observer. In order to create an intersection observer, all we need to do is listen for the intersection observer event to occur and trigger a callback function or handler to run when such an event occurs.

The intersection observer event is a browser event similar to the document event category, which includes the DOMContentLoaded event.

Note: For intersection events, we need to specify the elements to which the intersection is to be applied. This element is often called the root element. However, if no root element is specified, it means we intend to target the entire browser window.

Additionally, we need to specify a whitespace for the root element (if provided) so that its shape or size can be easily changed on the intersection if necessary. Let's see an example to understand it better:

let options = {
root: null,
rootMargin: 10px,
threshold: 1.0
}

let observer  = new IntersectionObserver (options, callback);
Copy after login

In the above code snippet, we see a simple use case for creating an observer. optionsObject helps us define custom properties of the target.

Here, the threshold attribute in the options object indicates when the callback is triggered. Its default value is 0, which means that once the user approaches the target element and it becomes visible, the callback will be triggered.

On the other hand, the root element is the parent element that acts as the viewport of the target element when it becomes visible to the user as they scroll the web page. Note that if root is set to empty, the parent element will automatically become the viewport.

Finally, rootMargin helps set the margin around the root element. For example, you may need to adjust the size, margins, or dimensions of the target element before calculating the intersection between it and the parent element/viewport.

Also, the callback that accepts two input parameters includes a list of intersectionObserverEntry objects that we intend to apply to the target element and the observer that calls the callback.

The signature of the callback is as follows:

let callback = (entries, observer) => {
entries.forEach(entry => {
If (entry.isIntersection) {
// do some magic here
}
// and some other methods
})
}
Copy after login

The intersectionObserverEntry object indicates that there is an intersection between the parent element and the target element. It has a bunch of properties in the API, including isIntersection, intersectionRatio, intersectionRect, target, time ,wait.

We need to target a specific DOM element and trigger the callback function when it intersects the parent element. An example of a target DOM element is shown in the following code snippet:

let target = document.querySelector("#targetElement");
Copy after login

In the above code snippet, we have created a target element and assigned a variable to it. After that, we observe the target element using the observe method on the intersectionObserver constructor/function signature as follows:

// start observing for changes on the target element
observer.observe(target);
Copy after login

When the threshold set by the observer for the target is reached, the callback will be triggered.

Finally, the observe() method tells the observer what target element to observe. Note that intersection observers also have a bunch of methods in its API: unObserve(), takeRecords(), observe(), etc. are some examples.

Benefits of Lazy Loading Technology

Now, we must better understand why lazy loading of web content and assets is necessary. Let’s take a look at some further advantages of using this technology:

  • Build highly accessible web applications. Discussions about web accessibility are top of mind today. Using this technique will definitely help in building a wider platform with

  • high user retention. If the web platform is relevant to driving business goals and delivering value, then implementing this technology will help make the platform more user-friendly. Web standards will thank you later!

  • As a developer, you may need to implement infinite scrolling on the web platform. Understanding this concept will go a long way in providing immediate business value

Implementing Lazy Loading

Let’s Let’s look at a simple example of lazy loading images on a web page. We will start by customizing the options object for the target element and the intersection we intend to observe:

let  options = {
root: document.querySelector('.root'),
rootMargin: '0px, 0px, 100px, 0px'
};
Copy after login

Now, for the target element, let's target a few images:

let  images = [...document.querySelectorAll('.targetImages')];
Copy after login

Now, let's see Look at the implementation callback:

const callback = (entries) => {

entries.forEach(entry => {
 If (entry.isIntersecting) {
    observer.unObserve('entry.target');
}
// handle other code logic here 
})
}
Copy after login

We can continue to call the intersection observer constructor to observe the target element, based on the customization specified in its options object:

let observer = new intersectionObserver(options, callback);
Copy after login

Finally, we can observe the object to be observed Target element:

images.forEach(image => {
observer.observe(image);
})
Copy after login

Note: For simplicity, the HTML and CSS code are not included here. You can learn more about how to implement this technique by viewing this example in the MDN documentation.

Summary

Now when we have a bunch of images or videos on a web page and load them on browser DOM initialization, this The advantages of this technology will be very obvious. As developers, we have a responsibility to ensure optimal performance of the platforms we manage or maintain, especially when they are tied to business goals.

As a web performance technology, lazy loading helps solve this type of problem.

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Learn more about lazy loading in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:logrocket.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template