Resource Lazy Loading With Angular

Resource Lazy Loading With Angular

lazyloadA lot of modern web applications are using Angular to power their apps. It is a platform to allow us to create single page applications that deliver a very fluid user experience compared to traditional methods in the old days. Although it is a great framework, there are some pain points. One of the thing we found is, Angular 1.x does not come with lazy loading built-in. Much of the resources, such as JavaScript, are needed to be loaded up-front, usually on the homepage of the site (for single page application). Most of the time, you need to includes all of the JavaScripts for the entire site on page load, even though you might not visit the page that use that JavaScript. This becomes quite a problem since it increase the amount of code the browser needed to load just for the app to run. The problem becomes even more dramatic for mobile site where every second of loading time counts.

Using ocLazyLoad in your project

Luckily for our problem, there is a library out there to solve this issue and save us from our headache. The ocLacyLoad library is designed to do just that. It is an open source project that is gaining popularity in recent days. You can visit their website here [].

The library is a nice addition to Angular. This allow us to load the resource that we want just when we need it, not before. So, we don’t have to define a gigantic script block that loads pretty much every single JavaScripts in the site. You can define those resources separately where it relevant, such as when you define Anuglar route. This helps quite a bit with code maintainability.

For example, let’s take a look at this Angular route.


If you use Angular ui-router, this script block defines a state for the route to contact us page. Some of us visit contact us page, and some of us don’t. We should just load the page HTML and JavaScript right when you visit contact us page, not when you visit the homepage.

To solve our problem, we define a ‘resolve’ parameter for the state. Before loading the state, Angular will determine the value of this parameter. We can define the required resources for the page here. In this case, we loads ‘ContactUsController.js’ right when we need it. That’s it. Our problem is gone.