Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6/7 by default uses Eager/Lazy loading? [closed]

As the title says, do we need to manually implement Lazy Loading for the modules or does Angular 6/7 does it by default?

like image 777
Henry Avatar asked Dec 08 '22 13:12

Henry


2 Answers

Angular by default uses eager loading unless specified otherwise.

To implement Lazy Loading, following things need to be specified to the RouterModule:

  1. A route config object with loadChildren instead of component. The value assigned to it would be the relative path to the Lazy Loaded Module, followed by # followed by the name of the module.

  2. The Lazy loaded module should also implement a routing module in it and in there, it should call forChild instead of forRoot.

There's a very nice guide provided on Angular's Official Docs that you can follow to implement Lazy Loading of modules.

Here's a Sample StackBlitz that you can follow to implement Lazy Loading.

like image 65
SiddAjmera Avatar answered Dec 28 '22 07:12

SiddAjmera


When you build an application (with ng build) it bundles it into several *.js script files and adds a reference to those script files to your index.html file. Those are the files you deploy to a backend server.

When a user accesses your site (www.yoursite.com), it locates the server hosting the site and pulls down the index.html file and all of the referenced script files containing all of your code. That code is then loaded in the browser.

Lazy loading involves bundling your application into additional bundles such that not all of it is pulled down when the index.html file comes down. This improves the "first load" of your page for the user. Other bundles are then pulled down "on demand" (meaning when the user access a route on the lazy loaded path) or async in the background after the initial load.

By default, Angular does not do lazy loading. It is something you define.

First, you divide your application into Angular modules. The lazy loading is defined by module. Each module defines a set of related components, directives, and pipes.

Then you use a specific syntax to lazy load those modules using syntax in the route configuration like this:

  {
    path: 'products',
    loadChildren: './products/product.module#ProductModule'
  },

Angular then bundles each lazy loaded module into its own script file separate from the scripts referenced in the index.html file.

You can find out more here: https://angular.io/guide/lazy-loading-ngmodules

like image 20
DeborahK Avatar answered Dec 28 '22 06:12

DeborahK