Understanding Angular Universal

Angular Universal is a project that's used for rendering Angular applications on the server side. This is a great way to improve the performance of our application and also add additional features to our application to make it more scrapable and sharable on search engines and social media.

Before we understand how this is done, let's go back and see how our application is viewed by rendering it. Our application, when requested, will return an HTML file with links to CSS and JavaScript, and if we look into our body, we will see only the root element.

To see this, open your application in a web browser, right-click anywhere, and click on View page source, which will open a new tab with the content that the server sends for our page.

You will see a body with a single element, app-root, without any content rendered in it, like so:

<body>
<app-root></app-root>
</body>

When the browser parses the HTML, it will download the CSS and JavaScript that was requested in the HTML file. After the JavaScript has been downloaded and parsed, it will run all the JavaScript code and render our app-root component. 

Here, the end user has to wait for the JavaScript code to be loaded, parsed, and run before they see anything on the browser. Similarly, search engines scrape your HTML file and get content from it. Only a few search engines, such as Google and Bing, can run JavaScript and scrape the content of your application. If you were building an application that you wanted to be scraped by search engines, then you probably want the entirety of its content in the HTML file, even before the JavaScript runs.

Angular is built in such a way that it does not have to run only on the browser. Angular is not tied to the Document Object Model (DOM), and it can run on any other platform that is supported—even a native mobile application. Angular provides a package called platform-browser-dynamic so that you can run the application on a browser. To run an Angular application heedlessly on a server, Angular provides a module called platform-server to render our application on the server. In this chapter, we will use Express, which is a Node.js framework for servers. Once we have rendered our application on our browser, search engines will be able to scrape the content of the web page, thereby allowing us to optimize our application for search engines.

Now that we understand why we need Angular Universal, let's deploy our application on ZEIT Now and do some performance analysis using Lighthouse.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.15.15