Detailed explanation of Hydration concept for Angular applications

Hydration concept for Angular applications

The concept of hydration is a key concept in Angular applications and relates to how the Angular framework operates in client-side rendering (CSR). To deeply understand Hydration, you first need to understand the basic difference between CSR and SSR (Server-side rendering, server-side rendering), and how Angular uses Hydration to improve CSR performance. This article will explain the concept of Hydration for Angular applications in detail and illustrate it with examples.

Basic Differences between CSR and SSR

Before understanding Hydration, let us briefly review the basic differences between CSR and SSR.

  • CSR (Client-side Rendering) : In CSR, the entire application building and rendering happens in the client browser. When a user accesses a CSR application, the browser downloads the application's JavaScript code and then executes the code on the user's device to render the page. The advantage of this approach is that it can achieve dynamic interaction on the client side, but it also has performance challenges because a large amount of JavaScript code needs to be downloaded when loading for the first time, resulting in a longer page loading time.

  • SSR (Server-side Rendering) : In SSR, when the server receives a client request, it pre-renders the HTML content on the server and sends it to the client browser. This means users will see content faster because they don't have to wait for a bunch of JavaScript code to download and execute. However, compared with CSR, SSR may cause increased server load in complex applications and has certain limitations on realizing certain interactive functions.

Angular CSR and SSR

Angular supports two rendering modes: CSR and SSR. By default, Angular applications operate in CSR mode, which means the entire rendering process occurs client-side. But in some cases, if you need better first-screen loading performance or SEO (search engine optimization) requirements, you can choose to use SSR.

In Angular, CSR applications are typically launched using:

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

The SSR application is started using:

platformServer().bootstrapModule(AppModule)
  .then(moduleRef => {
    
    
    const appRef = moduleRef.injector.get(ApplicationRef);
    const state = moduleRef.injector.get(PlatformState);
    appRef.isStable.pipe(
      first(isStable => isStable === true),
    ).subscribe(() => {
    
    
      state.renderToString().then(html => {
    
    
        console.log(html); // 在服务器上渲染的HTML
        moduleRef.destroy();
      });
    });
  });

In CSR mode, the initial load of an Angular application will include some basic HTML structure and a JavaScript bundle (usually containing the entire application's code), which is then run in the browser to render the complete page.

But there is a performance issue involved: the downloading and execution of the JavaScript package may take a certain amount of time, during which the user will see a blank page or loading indicator. This is exactly where the Hydration concept starts.

Behind the concept of Hydration

The core idea of ​​Hydration is to display content as quickly as possible in a CSR application without having to wait for the entire JavaScript package to be downloaded and executed. To do this, Angular introduces a mechanism that enables applications to load and populate content progressively on the browser side.

Specifically, when an Angular application is launched in CSR mode, it embeds some initial HTML content into the server-generated HTML, which is immediately displayed on the browser side. The JavaScript package is then downloaded and executed in the background. Once the JavaScript bundle is downloaded and ready, it "hydrates" the initial HTML content into interactive Angular components.

This means that users can still interact with content on the page while waiting for the JavaScript package to download and execute. The benefit of Hydration is improved user-perceived loading speed because the page displays content earlier while still allowing the app to load and initialize in the background.

How Hydration works

To understand how Hydration works, let’s take a deeper look at its steps:

  1. Server-side rendering (SSR) generates initial HTML : In server-side rendering, the initial HTML content of the Angular application is generated and includes some special markup to identify which parts need to be hydrated.

  2. Initial HTML sent to client : The generated initial HTML content is sent to the client browser with the response.

  3. Client downloads JavaScript package : The browser starts downloading the JavaScript package of the Angular application. This package contains the application code, components and modules.

  4. Execution of JavaScript package : Once the JavaScript package is downloaded, the browser will start executing it. During execution, the Angular framework recognizes special tags in the initial HTML and converts these tags into Angular components.

  5. Hydration : When the Angular framework hydrates the initial HTML content, it replaces that content with actual Angular components and establishes the ability to interact with those components. This means that users can interact with content on the page without having to wait for the entire JavaScript bundle to load and execute.

Hydration example

To better understand Hydration, let us demonstrate how it works through a simple example. Let's say we have an Angular application that contains a simple component that displays the user's

Name. The initial HTML for this component might look like this:

<!-- 初始HTML -->
<app-root>
  <app-user-name>Loading...</app-user-name>
</app-root>

In this example, <app-user-name>it's an Angular component that displays the user's name. The initial HTML contains a placeholder text "Loading..." because before hydration, the JavaScript package has not yet been downloaded and executed.

Now, let's see how Hydration is applied to this example:

  1. Server-side rendering (SSR) generates the initial HTML and sends it to the client.
<!-- 服务器生成的初始HTML -->
<app-root>
  <app-user-name _nghost-abc123>John Doe</app-user-name>
</app-root>

In this HTML, we can see that <app-user-name>the component's content has been populated with "John Doe" and has a special attribute _nghost-abc123that identifies this component.

  1. The client browser starts downloading the JavaScript package.

  2. During the execution of the JavaScript package, the Angular framework detected special tags in the initial HTML.

  3. The Angular framework replaces the special tags in the initial HTML with actual Angular components and establishes the interaction.

<!-- 水合后的HTML -->
<app-root>
  <app-user-name _nghost-abc123 _ngcontent-def456>John Doe</app-user-name>
</app-root>

In this HTML, <app-user-name>the component has been replaced by a component with Angular interactivity capabilities, and has two special properties _nghost-abc123and _ngcontent-def456, which are used to ensure the component's style isolation.

Now users can interact with content on the page without having to wait for the entire JavaScript bundle to load and execute.

Advantages and application scenarios of Hydration

The main benefit of Hydration is improved user-perceived loading speed, especially for CSR applications. Users are able to see and interact with content on the page faster without having to wait for the entire JavaScript package to download and execute.

Hydration is particularly useful in the following situations:

  1. Improve first-screen loading performance : For applications that want to quickly display content to users, Hydration can significantly improve first-screen loading performance and improve user experience.

  2. Improved SEO : For applications that require SEO, Hydration ensures that search engine crawlers can see the initial content of the page without having to wait for JavaScript to execute. This can improve search engine rankings.

  3. Progressive enhancement : Hydration supports the progressive enhancement strategy. Even if JavaScript loading fails or is disabled, the page will still work normally because the initial content has been generated during server-side rendering.

Hydration Challenges and Considerations

Although Hydration provides many performance benefits, there are also some challenges and considerations to be aware of:

  1. Additional complexity : Implementing Hydration requires introducing additional complexity into your Angular application, including adding special markup in the initial HTML to identify the parts that require hydration.

  2. Code Splitting : In order to achieve better Hydration effects, it is often necessary to split the code of the application into small pieces so that critical parts can be downloaded and executed faster.

  3. Performance monitoring : The performance of Hydration needs to be monitored to ensure that the download and execution of the JavaScript package does not cause performance problems.

  4. Initial state synchronization : Ensure that the content in the initial HTML is in sync with the state of subsequent JavaScript executions to avoid inconsistencies.

in conclusion

Hydration is a key concept in Angular applications that allows for increased user-perceived loading speed in CSR mode while retaining the interactivity of the application. By adding special tags to the initial HTML, Angular is able to display page content early while downloading and executing JavaScript packages in the background.

The implementation of Hydration requires a certain amount of complexity and consideration, but it can improve first-screen loading performance, improve SEO, support progressive enhancement strategies, and more. Understanding the working principle and application scenarios of Hydration can help developers better optimize the performance and user experience of Angular applications.

Supongo que te gusta

Origin blog.csdn.net/i042416/article/details/132910593
Recomendado
Clasificación