We've looked at lazy loading with ocLazyLoad previously, but what if we are using ui-router and want to lazy load modules when we change states?
[00:00] I'm going to refactor this really simple UI router demo to use lazy loading, so that when it changes state it loads in a module. Because you can see right now I have to require store up front. In my index, I have to require the store's script.
[00:16] Once that's all set up and you can see, once I click on this and I tell this state to go to the store state, which uses the store template and the store controller, I'll click this and you see it loads in this store template. I'm the store template and a message from the store controller.
[00:33] The first step in refactoring is simply replacing this store, which I'm including in here with lazy loads. Just use my live template there to use lazy load from a CDN. Going to go in to my demo here and instead of store, I'll use oc.lazyload and now I've excluded everything, the store script and the store module from my angular application. This should break completely when I try and use it, because it doesn't have that store module to use the store controller on it.
[01:07] The way that we're going to lazy load this is by using resolve and I have other videos on resolve you can go back and check out. To say briefly, that resolve takes an object with some properties that are functions and those functions return promises that must resolve before the state changes.
[01:28] Say return and we're going to need to inject oc.lazyload. So oc.lazyload, we're going to return a load, which is a promise, and this guy takes another object with a name. This is the name of the module, the module's name is store. If you look over here, this matches him and we also need to say that we're going to load that module.
[01:58] The files that we need for that module are store/store.js, so it's going to be this file. That's the one that has the store module in it.
[02:10] Once all of that is done, we can refresh, click me, and you can see everything worked out just fine. To inspect this, you can see, once I refresh and you check out the network, there's no mention of a store.js loaded in here. Once I hit click me, you can see it loads in store.js and also the template.
[02:33] That's how you refactor in to a lazy loading when you change states or changing URLs, Works the same way.