Optimizing an Angular app for performance involves both build-time and run-time strategies. Here's a comprehensive breakdown:
๐ Top Angular Performance Optimization Techniques
๐ง 1. Use Ahead-of-Time (AOT) Compilation
-
Compiles your code before the browser loads it.
-
Reduces bundle size and improves startup time.
(AOT is enabled by default in production mode.)
๐ฆ 2. Enable Production Mode
-
Disables development-specific checks and change detection warnings.
๐ณ 3. Tree Shaking & Lazy Loading
-
Tree shaking removes unused code during build.
-
Lazy loading defers loading feature modules until they're needed.
๐ข 4. Avoid Unnecessary Change Detection
-
Use
ChangeDetectionStrategy.OnPush
for components where inputs are immutable.
๐งผ 5. Optimize Template Expressions
-
Keep expressions in templates simple and fast.
-
Avoid calling functions in templates (they get called on every change detection).
๐ 6. TrackBy in ngFor
-
Prevents Angular from re-rendering entire lists unnecessarily.
๐พ 7. Preload Critical Resources & Use Lazy Loading Wisely
-
Use
PreloadAllModules
strategy to preload non-critical modules in the background.
๐งฑ 8. Minimize Bundle Size
-
Use tools like source-map-explorer to analyze your bundles:
-
Remove unused imports, third-party packages, and polyfills.
๐ 9. Optimize Images & Assets
-
Use optimized image formats (
webp
,avif
) -
Lazy-load large images and components
๐งช 10. Use Service Workers (PWA)
-
Enable caching with Angular Service Workers to serve files faster.
✅ Bonus Tips
-
Avoid memory leaks by unsubscribing from observables.
-
Use
trackBy
,async pipe
, anddebounceTime
in forms and search inputs. -
Avoid frequent
console.log()
in production.