Lazy Load Modal Components in Angular

Netanel Basal
Netanel Basal
Published in
2 min readAug 17, 2020

--

Using modals is one of the most popular UX concepts, which almost every application uses. In most cases, we’ll open the modal only when a user triggers a specific action.

If we think about it, it would be a waste to add the modal’s code to our initial bundle, because each client would have to download and parse it, even though they probably wouldn’t have cause to use it.

A better course of action would be to lazy load the modal’s code when the user initiates the action. Let’s see how easy it is to do that with Ivy:

When the user clicks on the button, we load the UsersManager component, passing it to our dialog service. We also use the Webpack magic comment webpackPrefetch. This will result in <link rel=”prefetch” href=”users-manager-chunk.js”> being appended in the head of the page, which will instruct the browser to prefetch in idle time the users-manager-chunk.js file.

I’d use prefetch for modals whose chances of opening are high. This way, it’ll not only reduce the initial load of the application, but the modals would also open without a tiny delay.

If you’re not familiar with lazy load components in Ivy, you can read the following article:

🚀 In Case You Missed It

Here are a few of my open source projects:

  • Akita: State Management Tailored-Made for JS Applications
  • Spectator: A Powerful Tool to Simplify Your Angular Tests
  • Transloco: The Internationalization library Angular
  • error-tailer — Seamless form errors for Angular applications
  • Forms Manager: The Foundation for Proper Form Management in Angular
  • Cashew: A flexible and straightforward library that caches HTTP requests
  • Error Tailor — Seamless form errors for Angular applications

And many more!

Follow me on Medium or Twitter to read more about Angular, Akita and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.