Code Optimization Techniques in Angular
Code Optimization Techniques in Angular
03 December 2021
Nowadays we always try to optimize our applications to make them faster, provide better user experience or update old code.
Optimization in an application could be reached by passing/adding some points, like: Correct decomposition of components;
Using change detection strategy OnPush; To Manage all subscriptions in the project.
There are variety of practices we can use, Two of the most popular ones are:
- Minification and dead code elimination
- Code-splitting
Code-splitting with Angular
There are two main approaches to code-splitting:
- Component level code-splitting
- Route level code-splitting
The basic difference between these two approaches is that with component level splitting,
we load individual components lazily without a route navigation.
Component-level code-splitting:
In component level you move components to their own JavaScript chunks and load them lazily when they are needed.
Route-level code-splitting:
We load the individual routes lazily. This technique involves boilerplate code. To creating a lazy route manually, we need to:
- Create a new module
- With load Children, declare a lazy route in a parent module
- Create a new component in the lazy loaded module
- Specify an eager route declaration in the lazy module
Performance budgets
To monitor our apps over time, Angular CLI supports performance budgets. The budget allow us to
Declare the boundaries in which the production bundles of our app can grow.
Efficient serving
Looking at datasets many Angular apps running into the wild, we have noticed that
over 25% of them do not use content compression, To allow developers to deliver fast Angular
apps from end-to-end as part of Angular CLI version 8.3 we will introduce a command called deploy.
PreLoading
The risk with this strategy is, in an application with many modules, it may increase the network consumption and block.
The main thread while Angular registers the routes of the preloaded modules.
we can apply more advanced preloading techniques:
Quick-link — Preload only when modules associated with visible links in the viewport
Predictive prefetching — Preload only when the modules that are likely to be needed.
“Angular executes an impure pipe when each component change their detection cycle.
An impure pipe is often, as every keystroke or mouse-move.”