In one of my previous articles, I showed how to load ECMAScript modules on demand using the typescript import() function.

Although in most cases you can make do by using this functionality, there are still cases where you’ll need to use an old library that doesn’t supports JS modules.

Real World Use Case

For example, in one of my most recent projects, I was required to add the ace editor. It would be a waste to add the library to our initial bundle, because each client would have to download and parse it, even though he probably wouldn’t have cause to use it.

A better course of action would be to lazy load this library when the user initiates an action or navigates to a state where the library is required.

Let’s see how we can do this.

Create the Directive

We’ll create a directive that will load the ace library from the /assets folder and initialize it.

Let’s take a look at the waitForAce() method implementation:

It’s time to leverage the power of RxJS to help us handle three occurrences:

The first request made in order to load the ace library and inject the source code into the page. Subsequent requests, which might occur if we have multiple instances of the same directive. In this case, we need to know that a request has already been made and poll until we discover that ace has been defined. Ace has been defined.

Note that I prefer the usage of timer(0) instead of the of() observable as I want to be consistent and always return an asynchronous response.

#Tip: If you prefer using repetitive timers you can change the interval to this:

A nice improvement as suggested in the comments is to run the interval outside the Angular zone.

Another approach suggested by Alexey Zuev is to use a ReplaySubject subject.

That’s it. Open the network tab and you should see that ace was loaded on demand.

You can also add a nice loading indicator by using the ngx-content-loader library.

Progress isn’t made by early risers. It’s made by lazy men trying to find easier ways to do something - Robert Heinlein

🔥 Last but Not Least, Have you Heard of Akita?

Akita is a state management pattern that we’ve developed here in Datorama. It’s been successfully used in a big data production environment and we’re continually adding features to it.

Akita encourages simplicity. It saves you the hassle of creating boilerplate code and offers powerful tools with a moderate learning curve, suitable for both experienced and inexperienced developers alike.

I highly recommend checking it out.

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