One of the main advantages offered by a SPA application is to try to transmit a similar experience to the user, of that of a desktop application from the web world, eliminating delays in intra-page navigation and avoiding reloads of these to each data transmission server. The app runs completely in the user’s browser.

These applications, just like Angular, generate a “package” JavaScript with all the content of the web in a file, including both the HTML of the views and the JavaScript code with its logic, and this file can grow alarmingly. Usually, in the creation of the deployment package we apply a process to minify and uglifiy, in order to reduce the size of the javascript file. Even so, the size of the file can be too large causing the initial load of the application to affect the overall user experience. Angular applies other techniques to further reduce the packet size, such as tree-shaking. However, despite these efforts, it is still insufficient.

To solve this, Angular allows the division of the different business units that can compose the application in Modules and through the internal routing engine allows the loading of each of these modules separately. In this way we reduce the initial size of the package, and in turn reduce the loading time of the application. This is what we call lazy-loading or lazy loading: i.e. we only load the module when we need it.

Lets have a look at an example, with the routing module of an Angular application, in which we apply lazy-loading for loading the Admin and Users modules:


The first thing to note is that, when defining the routing module, we are applying a loading strategy for the modules, in this case we are saying that after starting the app request the different modules that make up the background application, we apply a PreloadAllModules strategy. in this way we reduce the access time to the pages that make up these modules since they have been loaded without penalty for the user. But we could also have told him not to preload and they were requested on demand. To request the modules on demand, we apply a NoPreloading strategy

The second thing we see is that we are defining a path for each of the modules, and we indicate the path of the module and the name of the module that defines the functionality:
On the other hand, the routing of each of the modules has to define the routes by means of the initialization method forChild. We can see an example of how the routing would be for the user module proposed in the previous example:In this way, we can divide our Angular app into small pieces that are loaded in the background and in a transparent way for the user and improving the loading time.