What is Angular application server-side pre-rendering technology - prerendering

Angular Server Prerendering: Build faster and more user-friendly web applications

Angular is a powerful front-end framework for building modern web applications. However, as an application grows in size, performance issues may arise. In order to improve the performance and user experience of Angular applications, developers can adopt various techniques and methods. One of them is server-side prerendering, and this article will introduce this concept in detail and provide examples to illustrate its uses and advantages.

What is server-side prerendering?

Server-side pre-rendering, often referred to as "SSR" (Server-Side Rendering), is a technology used to improve web application performance and search engine optimization (SEO). It is opposed to traditional client-side rendering (Client-Side Rendering). In client-side rendering, the initialization and rendering of the application occurs in the user's browser, while in server-side pre-rendering, the initialization and partial rendering of the application occur on the server. This means that before sending the HTML to the browser, the server performs some of the Angular app's initial rendering work on the backend to produce a rendered HTML page. This HTML page can be presented directly to the user without waiting for JavaScript to load and execute.

The main advantages of server-side pre-rendering are:

  1. Faster load times : Since the server performs the initial rendering on the backend, users can see content faster. This is critical to improving user experience, especially on devices with low bandwidth or limited performance.

  2. SEO Friendly : Search engine crawlers can index and understand rendered HTML pages more easily, thus improving your app’s ranking in search results. This is very important for online businesses.

  3. Better performance : Reduced work required for client-side rendering, allowing browsers to load and interact faster. This is very helpful in reducing bounce rates and improving user retention.

Below, we will use a concrete example to demonstrate how server-side pre-rendering works.

Example: Angular server-side prerendering

In this example, we will use Angular framework and Angular Universal library to implement server-side pre-rendering. Let's say we are building a blog site with a list of articles and an article details page.

Step 1: Create Angular App

First, we create a basic Angular application. We can use Angular CLI to quickly generate the project skeleton:

ng new my-blog-app

Step 2: Install Angular Universal

Next, we need to install the Angular Universal library, which will help us implement server-side pre-rendering. Execute the following command in the project root directory:

ng add @nguniversal/express-engine

This command will automatically configure Angular Universal for us and generate the files and code required for server-side rendering.

Step 3: Create a pre-rendered route

In Angular Universal, we need to define which routes should be pre-rendered on the server side. For example, we might want article details pages to be pre-rendered server-side to provide faster loading times and SEO optimization. We can src/app/app.server.module.tsdefine prerender routes by editing the file:

// app.server.module.ts

import {
    
     NgModule } from '@angular/core';
import {
    
     ServerModule, ServerTransferStateModule } from '@angular/platform-server';
import {
    
     ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';

import {
    
     AppModule } from './app.module';
import {
    
     AppComponent } from './app.component';

@NgModule({
    
    
  imports: [
    AppModule,
    ServerModule,
    ModuleMapLoaderModule,
    ServerTransferStateModule,
  ],
  bootstrap: [AppComponent],
})
export class AppServerModule {
    
    }

Step 4: Create a pre-rendering service

Next, we create a prerendering service that will perform the initial rendering on the server side and generate the HTML page. We can src/app/prerender.service.tscreate this service in a file:

// prerender.service.ts

import {
    
     Injectable } from '@angular/core';
import {
    
     renderModuleFactory } from '@angular/platform-server';
import {
    
     enableProdMode } from '@angular/core';
import {
    
     APP_BASE_HREF } from '@angular/common';
import {
    
     createServerRenderer, RenderResult } from 'aspnet-prerendering';

import {
    
     AppServerModule } from './app.server.module';

enableProdMode();

@Injectable({
    
     providedIn: 'root' })
export class PrerenderService {
    
    
  public async render(params: any): Promise<RenderResult> {
    
    
    const {
    
     AppServerModuleNgFactory, LAZY_MODULE_MAP } = AppServerModule;
    const options = {
    
    
      document: params.data.originalHtml,
      url: params.url,
      extraProviders: [
        {
    
     provide: APP_BASE_HREF, useValue: params.baseUrl },
        {
    
     provide: 'BASE_URL', useValue: params.origin + params.baseUrl },
      ],
    };

    const renderModule = createServerRenderer((moduleFactory: any) => {
    
    
      return renderModuleFactory(moduleFactory, options);
    });

    return new Promise<RenderResult>((resolve, reject) => {
    
    
      renderModule(AppServerModuleNgFactory, {
    
    
        document: params.data.originalHtml,
        url: params.url,
      }).then((html: string) => {
    
    
        resolve({
    
     html });
      }, reject);
    });
  }
}

Step 5: Use a prerendering service

Finally, we use the prerendering service in a server-side route handler to handle specific routes. Here is the code for a sample Express.js route handler:

// server.ts

import 'zone.js/dist/zone-node';
import 'reflect-metadata';

import {
    
     enableProdMode } from '@angular/core';
import * as express from 'express';
import {
    
     ngExpressEngine } from '@nguniversal/

express-engine';
import {
    
     join } from 'path';
import {
    
     AppServerModule } from './src/main.server';

enableProdMode();

const app = express();

app.engine(
  'html',
  ngExpressEngine({
    
    
    bootstrap: AppServerModule,
  })
);

app.set('view engine', 'html');
app.set('views', join(__dirname, 'dist/browser'));

app.get('*.*', express.static(join(__dirname, 'dist/browser')));

app.get('*', (req, res) => {
    
    
  // 使用预渲染服务处理请求
  const prerenderService = new PrerenderService();
  prerenderService
    .render({
    
    
      url: req.url,
      baseUrl: '/',
      origin: req.protocol + '://' + req.get('host'),
      data: {
    
    
        originalHtml: '',
      },
    })
    .then(({
     
      html }) => {
    
    
      res.render('index', {
    
     req, res, html });
    })
    .catch((error) => {
    
    
      console.error(error);
      res.status(500).send('Internal Server Error');
    });
});

app.listen(3000, () => {
    
    
  console.log(`Server is listening on port 3000`);
});

In the above code, we use Angular Universal ngExpressEngineto handle routing and use it on routes that need to be pre-rendered PrerenderService.

Prerendering is a technology that renders pages on the server side. It can quickly provide fully rendered pages when users request them to improve user experience and search engine optimization (SEO).

For Angular or other single page applications (SPAs), they do a lot of JavaScript running on the client side to render the page. This means that when a user first requests a page, they need to download a large amount of JavaScript before the browser can start rendering the page. This causes the user to wait for a while before seeing the fully rendered page, which can have a negative impact on the user experience. Additionally, many search engine crawlers may not be able to fully execute JavaScript when indexing a page, which may result in a lower SEO ranking for the page.

Pre-rendering can solve these problems. When we do prerendering on the server side, we have already generated fully rendered HTML by the time the user requests the page. This means users can see a fully rendered page immediately without having to wait for JavaScript to run on the client side. Additionally, pre-rendered pages are more friendly to search engine crawlers because they can directly read the rendered HTML without executing JavaScript.

Take Angular Universal as an example, it is a key part of Angular that is used for pre-rendering on the server side. Here is a basic Angular Universal pre-rendering example:

First, we need to install Angular Universal's dependencies:

ng add @nguniversal/express-engine

This will add the necessary server-side rendering (SSR) support to our Angular project.

Then, in our Angular service, we can use renderModuleFactorythe function to pre-render our application. This function takes the Angular module factory and some options as parameters and returns a rendered HTML string.

import {
    
     renderModuleFactory } from '@angular/platform-server';
import {
    
     AppServerModuleNgFactory } from './app/app.server.module.ngfactory';

const html = await renderModuleFactory(AppServerModuleNgFactory, {
    
    
  document: '<app-root></app-root>',
  url: '/'
});

In this case, AppServerModuleNgFactoryit's the server-side version of our application, documentit's the HTML template we want to pre-render, and urlit's the route we want to render.

When our server receives a user's request, it can run the above code to generate pre-rendered HTML and then send this HTML to the user. The user's browser can immediately display this HTML, and then download and run JavaScript in the background so that the user can interact with the page.

in conclusion

Server-side pre-rendering is a powerful technique that can significantly improve the performance and SEO of your Angular applications. By moving the initial rendering server-side, we can achieve faster load times, a better user experience, and better search engine rankings. While setting up server-side pre-rendering may require some extra work, it can pay huge dividends, especially for web applications that need to handle large amounts of content and important SEO.

Hopefully this article has provided a detailed understanding of Angular server-side pre-rendering and demonstrated with examples how to implement it. Whether you are building a blog site or a complex enterprise application, server-side pre-rendering is an option worth considering and can significantly improve user experience and application performance. If you use Angular to build web applications, you may want to consider server-side pre-rendering to optimize your application.

Guess you like

Origin blog.csdn.net/i042416/article/details/133514982