ITKarma picture
Snail steampunk by Avi-li

Team Mail.ru Cloud Solutions translated an article about what lazy loading means in three front-end frameworks: Angular, React, and Vue.js. Further text on behalf of the author.

One of my favorite terms today is “lazy loading.” Honestly, when I heard him a few years ago, I smiled. In this article, I will examine what exactly this term means in relation to the three most commonly used front-end frameworks: Angular, React, and Vue.js.

Impatient download versus lazy


Impatient download means downloading each component of a particular application, which creates potential performance bottlenecks. Lazy loading ensures that this component is downloaded only when necessary, and not a second earlier.

Now you might think: this is great, the application will become faster, it will load faster. However, if your application has a module or component, the execution and loading of which takes considerable time, this still means slowing down the application. For this reason, you can use preloading a component in the background. This technique requires a separate article - I will not go into details here, but simply introduce you to this concept near the end.

About sample projects for example


Examples of applications created in all three frameworks are very similar. Each of them shows the following two things:

  • how to use lazy component loading inside the page;
  • how to use lazy component loading using routing.

To effectively visualize lazy loading, the demo application (component) will calculate the 42nd Fibonacci number. Mathematical operations are considered blocking - this means that our program cannot advance further; it should return the result of the calculation. This strategy is only used to simulate what happens if there is a piece of code that takes a long time to execute and what effect it has on the overall experience of using the application.

To access the project, please visit the GitHub repository .

Angular


Let's start our discussion with Angular, because this front-end framework has a feature when it comes to lazy component loading. In fact, in Angular, a module is the smallest logical unit that we can consider for lazy loading through routing, because components always belong to modules.

Fibonacci component


This is how our component looks in Angular:

ITKarma picture

Since this is a separate component and it already belongs to the Angular root component, we can upload it to the page.

Download component per page


First, let's look at how to load a component onto a page. To do this, we add the following:

ITKarma picture

Together with the following TypeScript code:

ITKarma picture

What is really interesting in this situation is that the CDMY0CDMY component will only load if CDMY1CDMY is equal to CDMY2CDMY. This means that lazy loading can only be controlled using the CDMY3CDMY directive.This is because Angular does not just show or hide the component in the DOM - it adds or removes it based on the specified condition.

Lazy loading or routing


While discussing lazy loading through routing in Angular, we found that you need to create a function module ( more about Angular function modules ).

You can create a functional module in our application together with the second component using the Angular CLI: CDMY4CDMY.

After creating the module, we can assign a component to it, and then add it to the main routing module (CDMY5CDMY):

ITKarma picture

Please note that we use CDMY6CDMY and import the module as part of the route definition. This means that the module will be loaded only when the corresponding route is active.

Compare the code above with this:

ITKarma picture

This code will download CDMY7CDMY immediately. This will cause a significant delay in the display of the main page of the application. Why lock the main page with an operation in a component that we don’t even see or use?

Here you can read more about lazy loading in Angular .

Vue


Now let's look at how to achieve lazy loading during development using the Vue.js. framework. Let's create a Vue application using the Vue CLI command line interface and add a new component. Take a look at what part of the CDMY8CDMY component will look like:

ITKarma picture

Please note : the reason we need to perform the calculation outside the CDMY9CDMY block is because otherwise we won’t be able to simulate the lock operation. Naturally, Vue.js has both the CDMY10CDMY property and the CDMY11CDMY property, which are available for components, which allows calling code only when creating a component.

Lazy loading of a single component


In Vue.js, we can use the CDMY12CDMY directive to add or remove an element from the DOM, and so lazily load the component. However, there are many more things we need to do when it comes to comparing Vue.js and Angular. Take a look at the following code:

ITKarma picture

This may seem like a logical way to do lazy loading, however when you open the page it becomes obvious that the initial loading time is really long. This is because the component is loaded immediately regardless of the CDMY13CDMY condition. In other words, we tell Vue to load all components regardless of whether they are added to the DOM.

Download performance will change significantly if we make the following changes to the CDMY14CDMY item:

ITKarma picture

By adding the inline-style CDMY15CDMY expression as part of the component property, we enable lazy loading for the CDMY16CDMY component. Now updating the application will mean that the main page loads really fast. Only when the CDMY17CDMY component is displayed on the main page is there some delay.

Lazy component loading or routing


Lazy component loading in Vue.js follows a similar pattern that we discussed earlier. Look at the router:

ITKarma picture

You may have used or seen such a router before in Vue applications.Although it is functional, you can observe the following problem. If we have a blocking operation in the CDMY18CDMY component, it will block the loading of the Home component.

To fix this problem, we can resort to the usual pattern and import the component into the route definition:

ITKarma picture

Now loading of the main page will not be blocked, and the CDMY19CDMY component is loaded only when the user selects the desired route.

There is more information about lazy loading in Vue.js .

React


Last but not least, let's look at how to achieve lazy loading in React. The application was created using the CLI CDMY20CDMY and, as in the previous examples, we have a component with some blocking operation:

ITKarma picture

Lazy loading of a single component


By default, as in the previous examples using other frameworks, importing components will mean impatient loading:

ITKarma picture

In the above example, even if the CDMY21CDMY component is not displayed, loading the application’s main page still takes a lot of time. To fix this, you need to tell React about the lazy loading of the component after the question mark. React has several helper tools, such as the Suspense component to display the placeholder during component loading and the CDMY22CDMY method, which loads the component lazily:

ITKarma picture

Making these changes to the application means that the CDMY23CDMY component will load quickly, and the CDMY24CDMY component will load only when the user asks for it.

Lazy loading or routing


The same approach applies to lazy component loading using routing, including the use of CDMY25CDMY and CDMY26CDMY:

ITKarma picture

Given the above router, in combination with the CDMY27CDMY operator, this means that the CDMY28CDMY component will be loaded immediately. Now, I hope, it is clear why this is not ideal. To enable lazy component loading through routing, you need to change the code to use the aforementioned component CDMY29CDMY and the CDMY30CDMY method:

ITKarma picture

There's more to lazy loading in React .

Checks through Developer Tools


To see what happens under the hood, we can use the DevTools panel of the browser.

What is discussed in this section is true for all the frameworks that are discussed in this article.

First of all, we can verify that when our application uses impatient loading, all JavaScript is loaded and executed by the browser. How can this be seen in DevTools? Clicking on the Fibonacci link does not load additional JavaScript.

Updating the code to use lazy loading will mean that less JavaScript will be loaded first. When the component loads, a new JavaScript request appears - this is the same fragment that we just requested.

Take a look at the screenshots below to see the status before and after. I also recommend that you run these samples yourself and play DevTools with them.

ITKarma picture

ITKarma picture

ITKarma picture

ITKarma picture

ITKarma picture

ITKarma picture

Еще одна вещь


Конечно, ленивая загрузка компонента не решает одну проблему: время выполнения для проблемного модуля. В нашем случае компонент, конечно, раздутый, поскольку он выполняет некоторые тяжелые математические вычисления, но независимо от этого пользователи все равно могут посещать адрес и сталкиваться с проблемами производительности.

Существуют определенные стратегии, которые помогут преодолеть эту проблему. Со всеми фреймворками мы можем использовать волшебные комментарии через Webpack для динамического добавления CDMY31CDMY (или CDMY32CDMY) через тег CDMY33CDMY на страницу. Просто поместите волшебные комментарии перед именем компонента, внутри импорта:

ITKarma picture

Это добавит в DOM тег CDMY34CDMY.

CDMY35CDMY в Webpack .

В заключение


Ленивая загрузка — принцип, который позволяет выбрать, какие компоненты будут загружены позже в приложении, чтобы обеспечить лучшую производительность. Это стратегия, которую можно выбрать вместо нетерпеливой загрузки, когда все компоненты загружаются одновременно, вызывая потенциальные проблемы с производительностью.

Что еще почитать по теме:

  1. Переиспользуемые компоненты React: как перестать писать одно и то же .
  2. Как избежать ошибок при разработке на React .
  3. Наш телеграм-канал с новостями о цифровой трансформации .
.

Source