An article exploring server-side rendering (SSR) in Angular
Dec 27, 2022 pm 07:24 PMGenerally speaking, ordinary Angular applications run in browsers, render pages in the DOM, and interact with users. Angular Universal renders on the server-side (Server-Side Rendering, SSR), generates static application web pages, and then displays them on the client. The advantage is that it can be rendered faster and provides a complete Content display can be provided to users before interaction. [Related tutorial recommendations: "angular tutorial"]
This article is completed in the Angular 14 environment. Some content may not be applicable to the new Angular version. Please refer to Angular official document.
Benefits of using SSR
More friendly to SEO
Although some websites including Google now Search engines and social media claim to already support crawling SPA (Single-Page Application) applications driven by JavaScript (JS), but the results seem to be unsatisfactory. The SEO performance of static HTML websites is still better than that of dynamic websites, which is also the view held by Angular's official website (Angular is owned by Google!).
Universal can generate a static version of the application without JS, and has better support for search, external links, and navigation.
Improve mobile performance
Some mobile devices may not support JS or have very limited support for JS, resulting in a very poor website access experience. In this case, we need to provide a JS-free version of the app to provide a better experience for users.
Display the homepage faster
For the user experience, the speed of displaying the homepage is crucial. According to eBay, every 100 milliseconds faster search results are displayed increases "add to cart" usage by 0.5%.
After using Universal, the home page of the application will be displayed to the user in a complete form. This is a pure HTML web page, which can be displayed even if JS is not supported. At this time, although the web page cannot handle browser events, it supports jumping throughrouterLink.
Add SSR to the project
Angular CLI can help us convert an ordinary Angular project into a project with SSR very conveniently. Creating a server-side application only requires one command:ng?add?@nguniversal/express-engine
It is recommended to commit all changes before running this command.This command will make the following modifications to the project:
- Add the server file:
- main.server .ts
- Server main program file
- app/app.server.module.ts
- Server application main module
- tsconfig. server.json
- TypeScript server configuration file
- server.ts
-
Express web server running file
- main.server .ts
- Modified file:
- package.json
- Add the dependencies required for SSR and run the script
- angular.json
- Add the configuration required to develop and build SSR applications
- package.json
package.json, some npm scripts will be automatically added:
dev:ssr is used to run the SSR version in the development environment;
serve:ssr is used to directly run the build or prerendered web page;
build:ssr is used to build the SSR version of the web page;
prerender Builds pre-rendered web pages. Different from
build, the HTML files of these pages will be generated based on the provided
routes.
Replacement of Browser API
Because Universal apps are not executed in the browser, some browser APIs or features will not be available. For example, server-side applications cannot use the global objectswindow,
document,
navigator,
location in the browser.
Location and
DOCUMENT.
window.location.href, and after changing it to SSR, the code is as follows:
import { Location } from '@angular/common'; export class AbmNavbarComponent implements OnInit{ // ctor 中注入 Location constructor(private _location:Location){ //... } ngOnInit() { // 打印當(dāng)前地址 console.log(this._location.path(true)); } }Similarly , for using
document.getElementById() to obtain DOM elements in the browser, after changing to SSR, the code is as follows:
import { DOCUMENT } from '@angular/common'; export class AbmFoxComponent implements OnInit{ // ctor 中注入 DOCUMENT constructor(@Inject(DOCUMENT) private _document: Document) { } ngOnInit() { // 獲取 id 為 fox-container 的 DOM const container = this._document.getElementById('fox-container'); } }
使用 URL 絕對(duì)地址
在 Angular SSR 應(yīng)用中,HTTP 請(qǐng)求的 URL 地址必須為 絕對(duì)地址(即,以 http/https
開頭的地址,不能是相對(duì)地址,如 /api/heros
)。Angular 官方推薦將請(qǐng)求的 URL 全路徑設(shè)置到 renderModule()
或 renderModuleFactory()
的 options
參數(shù)中。但是在 v14 自動(dòng)生成的代碼中,并沒有顯式調(diào)用這兩個(gè)方法的代碼。而通過讀 Http 請(qǐng)求的攔截,也可以達(dá)到同樣的效果。
下面我們先準(zhǔn)備一個(gè)攔截器,假設(shè)文件位于項(xiàng)目的 shared/universal-relative.interceptor.ts
路徑:
import { HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Inject, Injectable, Optional } from '@angular/core'; import { REQUEST } from '@nguniversal/express-engine/tokens'; import { Request } from 'express'; // 忽略大小寫檢查 const startsWithAny = (arr: string[] = []) => (value = '') => { return arr.some(test => value.toLowerCase().startsWith(test.toLowerCase())); }; // http, https, 相對(duì)協(xié)議地址 const isAbsoluteURL = startsWithAny(['http', '//']); @Injectable() export class UniversalRelativeInterceptor implements HttpInterceptor { constructor(@Optional() @Inject(REQUEST) protected request: Request) { } intercept(req: HttpRequest<any>, next: HttpHandler) { // 不是絕對(duì)地址的 URL if (!isAbsoluteURL(req.url)) { let protocolHost: string; if (this.request) { // 如果注入的 REQUEST 不為空,則從注入的 SSR REQUEST 中獲取協(xié)議和地址 protocolHost = `${this.request.protocol}://${this.request.get( 'host' )}`; } else { // 如果注入的 REQUEST 為空,比如在進(jìn)行 prerender build: // 這里需要添加自定義的地址前綴,比如我們的請(qǐng)求都是從 abmcode.com 來。 protocolHost = 'https://www.abmcode.com'; } const pathSeparator = !req.url.startsWith('/') ? '/' : ''; const url = protocolHost + pathSeparator + req.url; const serverRequest = req.clone({ url }); return next.handle(serverRequest); } else { return next.handle(req); } } }
然后在 app.server.module.ts
文件中 provide 出來:
import { UniversalRelativeInterceptor } from './shared/universal-relative.interceptor'; // ... 其他 imports @NgModule({ imports: [ AppModule, ServerModule, // 如果你用了 @angular/flext-layout,這里也需要引入服務(wù)端模塊 FlexLayoutServerModule, ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: UniversalRelativeInterceptor, multi: true } ], bootstrap: [AppComponent], }) export class AppServerModule { }
這樣任何對(duì)于相對(duì)地址的請(qǐng)求都會(huì)自動(dòng)轉(zhuǎn)換為絕對(duì)地址請(qǐng)求,在 SSR 的場景下不會(huì)再出問題。
Prerender 預(yù)渲染靜態(tài) HTML
經(jīng)過上面的步驟后,如果我們通過 npm run build:ssr
構(gòu)建項(xiàng)目,你會(huì)發(fā)現(xiàn)在 dist/<your project>/browser
下面只有 index.html
文件,打開文件查看,發(fā)現(xiàn)其中還有 <app-root></app-root>
這樣的元素,也就是說你的網(wǎng)頁內(nèi)容并沒有在 html 中生成。這是因?yàn)?Angular 使用了動(dòng)態(tài)路由,比如 /product/:id
這種路由,而頁面的渲染結(jié)果要經(jīng)過 JS 的執(zhí)行才能知道,因此,Angular 使用了 Express 作為 Web 服務(wù)器,能在服務(wù)端運(yùn)行時(shí)根據(jù)用戶請(qǐng)求(爬蟲請(qǐng)求)使用模板引擎生成靜態(tài) HTML 界面。
而 prerender
(npm run prerender
)會(huì)在構(gòu)建時(shí)生成靜態(tài) HTML 文件。比如我們做企業(yè)官網(wǎng),只有幾個(gè)頁面,那么我們可以使用預(yù)渲染技術(shù)生成這幾個(gè)頁面的靜態(tài) HTML 文件,避免在運(yùn)行時(shí)動(dòng)態(tài)生成,從而進(jìn)一步提升網(wǎng)頁的訪問速度和用戶體驗(yàn)。
預(yù)渲染路徑配置
需要進(jìn)行預(yù)渲染(預(yù)編譯 HTML)的網(wǎng)頁路徑,可以有幾種方式進(jìn)行提供:
通過命令行的附加參數(shù):
ng run <app-name>:prerender --routes /product/1 /product/2
如果路徑比較多,比如針對(duì)
product/:id
這種動(dòng)態(tài)路徑,則可以使用一個(gè)路徑文件:routes.txt
/products/1 /products/23 /products/145 /products/555
然后在命令行參數(shù)指定該文件:
ng run <app-name>:prerender --routes-file routes.txt
在項(xiàng)目的
angular.json
文件配置需要的路徑:"prerender": { "builder": "@nguniversal/builders:prerender", "options": { "routes": [ // 這里配置 "/", "/main/home", "/main/service", "/main/team", "/main/contact" ] },
配置完成后,重新執(zhí)行預(yù)渲染命令(npm run prerender
或者使用命令行參數(shù)則按照上面<1><2>中的命令執(zhí)行),編譯完成后,再打開 dist/<your project>/browser
下的 index.html
會(huì)發(fā)現(xiàn)里面沒有 <app-root></app-root>
了,取而代之的是主頁的實(shí)際內(nèi)容。同時(shí)也生成了相應(yīng)的路徑目錄以及各個(gè)目錄下的 index.html
子頁面文件。
SEO 優(yōu)化
SEO 的關(guān)鍵在于對(duì)網(wǎng)頁 title
,keywords
和 description
的收錄,因此對(duì)于我們想要讓搜索引擎收錄的網(wǎng)頁,可以修改代碼提供這些內(nèi)容。
在 Angular 14 中,如果路由界面通過 Routes
配置,可以將網(wǎng)頁的靜態(tài) title
直接寫在路由的配置中:
{ path: 'home', component: AbmHomeComponent, title: '<你想顯示在瀏覽器 tab 上的標(biāo)題>' },
另外,Angular 也提供了可注入的 Title
和 Meta
用于修改網(wǎng)頁的標(biāo)題和 meta 信息:
import { Meta, Title } from '@angular/platform-browser'; export class AbmHomeComponent implements OnInit { constructor( private _title: Title, private _meta: Meta, ) { } ngOnInit() { this._title.setTitle('<此頁的標(biāo)題>'); this._meta.addTags([ { name: 'keywords', content: '<此頁的 keywords,以英文逗號(hào)隔開>' }, { name: 'description', content: '<此頁的描述>' } ]); } }
總結(jié)
Angular 作為 SPA 企業(yè)級(jí)開發(fā)框架,在模塊化、團(tuán)隊(duì)合作開發(fā)方面有自己獨(dú)到的優(yōu)勢。在進(jìn)化到 v14 這個(gè)版本中提供了不依賴 NgModule
的獨(dú)立 Component
功能,進(jìn)一步簡化了模塊化的架構(gòu)。
Angular Universal 主要關(guān)注將 Angular App 如何進(jìn)行服務(wù)端渲染和生成靜態(tài) HTML,對(duì)于用戶交互復(fù)雜的 SPA 并不推薦使用 SSR。針對(duì)頁面數(shù)量較少、又有 SEO 需求的網(wǎng)站或系統(tǒng),則可以考慮使用 Universal 和 SSR 技術(shù)。
更多編程相關(guān)知識(shí),請(qǐng)?jiān)L問:編程教學(xué)!!
The above is the detailed content of An article exploring server-side rendering (SSR) in Angular. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

Do you know Angular Universal? It can help the website provide better SEO support!

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

The Angular project is too large, how to split it reasonably? The following article will introduce to you how to reasonably split Angular projects. I hope it will be helpful to you!
