🚀 Mastering Lazy Loading in Angular: A Step-by-Step Guide!

Paul Chesa
4 min readSep 15, 2024

--

If you’re building a large Angular application, you want it to load fast, right? Imagine you’re throwing a party 🎉 and you only want to serve snacks when guests arrive, not all at once, overwhelming your kitchen. Lazy loading in Angular works the same way. Instead of loading all your app’s features upfront, you load parts of it only when needed — like serving snacks to guests when they ask for it!

In this tutorial, we’ll explore how to implement lazy loading in Angular step by step.

🧐 What is Lazy Loading?

Lazy loading in Angular allows us to load JavaScript bundles asynchronously as users navigate through different routes. It’s like Angular saying, “Let’s not bring all the party snacks out at once. Let’s only bring out what’s needed when someone asks.”

Why is it important?

  • Faster initial load time 🚀
  • Better user experience 😊
  • Optimized resource usage 🔧

🏗 Step 1: Set Up Your Angular Project

Let’s start by creating an Angular app if you don’t already have one.

ng new lazy-loading-demo

Select Yes for Angular Routing and pick CSS as your style format (or any other you prefer).

After your project is set up, navigate into it:

cd lazy-loading-demo

🛤 Step 2: Define Feature Modules

Lazy loading typically involves dividing your application into modules, and loading them on demand. Let’s create two feature modules for this demo: products and cart.

ng generate module features/products --route products --module app.module
ng generate module features/cart --route cart --module app.module

This creates two modules (ProductsModule and CartModule) with routing automatically set up in your app-routing.module.ts file. Notice how Angular adds the routes for lazy loading:

const routes: Routes = [
{ path: 'products', loadChildren: () => import('./features/products/products.module').then(m => m.ProductsModule) },
{ path: 'cart', loadChildren: () => import('./features/cart/cart.module').then(m => m.CartModule) },
];

Here’s what’s happening: Instead of importing the modules directly, Angular will wait until you navigate to /products or /cart to load these modules. 🎉

🏎 Step 3: Create Components for the Modules

Now, let’s generate components inside these modules so we can see lazy loading in action.

ng generate component features/products/product-list
ng generate component features/cart/cart-details

Add some basic content to these components, so they display something when loaded. For instance, in the product-list.component.html:

<h2>Products List</h2>
<p>Here are some awesome products you can buy!</p>

And in the cart-details.component.html:

<h2>Your Cart</h2>
<p>This is your shopping cart. Ready to check out?</p>

🎯 Step 4: Adjust Feature Module Routing

Now, let’s configure the routing for these feature modules. Open the products-routing.module.ts file and add the route for the ProductListComponent:

const routes: Routes = [
{ path: '', component: ProductListComponent }
];

Do the same for the CartRoutingModule:

const routes: Routes = [
{ path: '', component: CartDetailsComponent }
];

🧠 Step 5: Test Lazy Loading!

At this point, you’re ready to test lazy loading. Run your Angular app:

ng serve

Open your browser and navigate to http://localhost:4200/products. Angular will load the ProductsModule lazily (i.e., only when you visit this route). Now, if you head over to /cart, it will load the CartModule on demand.

If you inspect the Network tab in the browser’s developer tools, you’ll notice that Angular is fetching separate JavaScript bundles for these routes. This means lazy loading is working! 🎉

🎨 Step 6: Preloading Lazy-Loaded Modules (Optional)

Lazy loading is great, but what if you want to load these modules in the background while the user is interacting with your app? You can enable preloading for lazy-loaded modules!

In app-routing.module.ts, modify the RouterModule import to include PreloadAllModules:

RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })

With this, Angular will preload the lazy-loaded modules after the initial load, ensuring they’re ready when the user navigates to them!

🛠 Bonus Tips

  • CanActivate Guard: You can protect your lazy-loaded routes using route guards, ensuring users have the right permissions before loading the module.
  • Lazy Loading Images: Just like routes, images can be lazy-loaded, making your app even more efficient.
  • Optimizing Lazy Loading: For large applications, consider lazy loading at multiple levels, such as within components, not just routes.

🎉 Conclusion

And there you have it! Lazy loading in Angular is like keeping your party snacks in the kitchen until your guests ask for them. It makes your app fast, efficient, and ready for scaling. By following these steps, you’re well on your way to building a blazing-fast Angular app that only loads what’s needed, when it’s needed. 🏎💨

Happy coding! 👨‍💻👩‍💻

--

--

Paul Chesa
Paul Chesa

Written by Paul Chesa

Angular developer | Frontend Developer | Proficient in Typescript and JavaScript | Parva res est

No responses yet