Loading AngularJS Components After Your Application Has Been Bootstrapped
Up until now, I have only ever defined my AngularJS components (ie, controllers, services, factories, etc.) before AngularJS has bootstrapped my JavaScript application. And, as it turns out, defining components after bootstrapping is somewhat tricky since it appears the given components don't get added to the right dependency-injection container (for reasons I don't fully understand at this time). Luckily, Ifeanyi Isitor has an awesome article on how to "provide" component definitions after bootstrapping. To help me wrap my head around his technique, I wanted to try to get it working in a far more simple context.
View this demo in my JavaScript-Demos project on GitHub.
The problem, as Ifeanyi points out, is that after your AngularJS application has been bootstrapped, you can only define new components using the relevant "providers". Furthermore, you can only gain access to these providers within the config() callbacks executed during the bootstrapping process. As such, you need to save a reference to these providers if you wish to load subsequent components after your AngularJS application has been bootstrapped.
In the following demo, I'm doing just that. Within the config() callback, I'm actually overwriting the original "shorthand" module methods with the provider-driven equivalents that can be used after bootstrapping. This way, the modules that I define after page-load don't have to use any special syntax - they can define components the same way you would pre-bootstrap.
In this demo, I have two subviews that are rendered using the ngSwitch and ngSwitchWhen directives. The "before" subview doesn't require any additional components to run. The "after" subview, on the other hand, relies on a number of components, including a Controller, that are being loaded after bootstrap.
The interweaving of components is overly complicated for this example since I wanted to make sure that Controllers, Services, Factories, Values, and Directives could all be defined post-bootstrap.
<!doctype html>
<html ng-app="Demo">
<head>
<meta charset="utf-8" />
<title>
Loading AngularJS Components After Application Bootstrap
</title>
<style type="text/css">
a[ ng-click ] {
cursor: pointer ;
user-select: none ;
-webkit-user-select: none ;
-moz-user-select: none ;
-ms-user-select: none ;
-o-user-select: none ;
text-decoration: underline ;
}
</style>
</head>
<body ng-controller="AppController">
<h1>
Loading AngularJS Components After Application Bootstrap
</h1>
<p>
<a ng-click="toggleSubview()">Toggle Subviews</a>
</p>
<!--
The "Before" subview doesn't need any additional assets;
however, the "After" subview relies on a number of assets
that will be loaded after the AngularJS application has been
bootstrapped.
-->
<div ng-switch="subview">
<div ng-switch-when="before" ng-include=" 'before.htm' "></div>
<div ng-switch-when="after" ng-include=" 'after.htm' "></div>
</div>
<!-- BEGIN: Templates For ngInclude. -->
<script type="text/ng-template" id="before.htm">
<p>
Before app bootstrap.
</p>
</script>
<script type="text/ng-template" id="after.htm">
<p ng-controller="LazyController" bn-italics>
{{ message }}
</p>
</script>
<!-- END: Templates For ngInclude. -->
<!-- Load jQuery and AngularJS. -->
<script type="text/javascript" src="../../vendor/jquery/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="../../vendor/angularjs/angular-1.0.7.min.js"></script>
<script type="text/javascript">
// Create an application module for our demo.
var app = angular.module( "Demo", [] );
// -------------------------------------------------- //
// -------------------------------------------------- //
// After the AngularJS has been bootstrapped, you can no longer
// use the normal module methods (ex, app.controller) to add
// components to the dependency-injection container. Instead,
// you have to use the relevant providers. Since those are only
// available during the config() method at initialization time,
// we have to keep a reference to them.
// --
// NOTE: This general idea is based on excellent article by
// Ifeanyi Isitor: http://ify.io/lazy-loading-in-angularjs/
app.config(
function( $controllerProvider, $provide, $compileProvider ) {
// Since the "shorthand" methods for component
// definitions are no longer valid, we can just
// override them to use the providers for post-
// bootstrap loading.
console.log( "Config method executed." );
// Let's keep the older references.
app._controller = app.controller;
app._service = app.service;
app._factory = app.factory;
app._value = app.value;
app._directive = app.directive;
// Provider-based controller.
app.controller = function( name, constructor ) {
$controllerProvider.register( name, constructor );
return( this );
};
// Provider-based service.
app.service = function( name, constructor ) {
$provide.service( name, constructor );
return( this );
};
// Provider-based factory.
app.factory = function( name, factory ) {
$provide.factory( name, factory );
return( this );
};
// Provider-based value.
app.value = function( name, value ) {
$provide.value( name, value );
return( this );
};
// Provider-based directive.
app.directive = function( name, factory ) {
$compileProvider.directive( name, factory );
return( this );
};
// NOTE: You can do the same thing with the "filter"
// and the "$filterProvider"; but, I don't really use
// custom filters.
}
);
// -------------------------------------------------- //
// -------------------------------------------------- //
// I control the root of the application.
app.controller(
"AppController",
function( $scope ) {
// Since this Controller will be instantiated once
// the application is bootstrapped, let's log it to
// the console so we can see the timing.
console.log( "Controller instantiated (after bootstrap)." );
// I determine which view is rendered.
$scope.subview = "before";
// ---
// PUBLIC METHODS.
// ---
// I toggle between the two different subviews.
$scope.toggleSubview = function() {
if ( $scope.subview === "before" ) {
$scope.subview = "after";
} else {
$scope.subview = "before";
}
}
}
);
// -------------------------------------------------- //
// -------------------------------------------------- //
// Once the DOM-Ready event has fired, we know that AngularJS
// will have bootstrapped the application. As such, we want to
// try adding our "lazy bindings" after the DOM-ready event.
$( lazyBindings );
// I define the modules after bootstrapping. Remember, inside
// of this function, the shorthand methods (ex, app.controller)
// NO LONGER POINTER to the core shorthands; instead, they
// point to the method definitions we defined in the config()
// method executed at application bootstrap.
function lazyBindings() {
console.log( "Lazy bindings added to application." );
// Lazy-loaded controller.
app.controller(
"LazyController",
function( $scope, uppercase, util ) {
$scope.message = util.emphasize(
uppercase( "After app bootstrap." )
);
}
);
// Lazy-loaded service.
app.service(
"util",
function( emphasize ) {
this.emphasize = emphasize;
}
);
// Lazy-loaded factory.
app.factory(
"emphasize",
function() {
return(
function( value ) {
return( value.replace( /\.$/, "!!!!" ) );
}
);
}
);
// Lazy-loaded value.
app.value(
"uppercase",
function( value ) {
return( value.toString().toUpperCase() );
}
);
// Lazy-loaded directive.
app.directive(
"bnItalics",
function() {
return(
function( $scope, element ) {
element.css( "font-style", "italic" );
}
);
}
);
}
</script>
</body>
</html>
When we run the above code, we get the following console output, demonstrating the order of operations that took place:
Config method executed.
Controller instantiated (after bootstrap).
Lazy bindings added to application.
As you can see, the lazy-loaded modules were defined after the app-controller was instantiated. This indicates that they were, indeed, loaded after the application was bootstrapped. Furthermore, the fact that the code runs (see video) shows us that the lazy-loaded modules were made available in the right dependency-injection container.
I think this is pretty cool stuff. Lazy-loading components in AngularJS is one thing; now, I have to figure out the best way to go about managing and loading these components at appropriate times. In his demo, Ifeanyi does this in the route-resolution; however, my routes are much "dumber" and don't know about anything other than request variables. Much more research and development to perform. And, huge thanks to Ifeanyi for paving the way!
Want to use code from this post? Check out the license.
Reader Comments
This is great Ben, and a lovely approach from Ifeanyi. I have noticed a few large MVC applications (Angular & Otherwise) that do certainly suffer a performance hit on the initial load which can be very frustrating.
I'd love to see something like this adopted in to the core framework in future, so the implementation can be as tidy as possible, and officially supported. It seems that a lazy-loading is a sensible approach moving forward, as the apps are only going to grow larger and larger.
@Robert,
Yeah, for real! I think InVision servers up close to 1MB in JavaScript on page load :( At least we split the "custom" JS from the "vendor" JS since the vendor JS very rarely changes. That way, when we have to rebuild the JS content, only the custom stuff has to be redownloaded (if the user already has the vendor stuff cached). Of course, if nothing is cached, it all gets downloaded.
As a next step, I want to look at using RequireJS to managing some lazy-loading using this technique.
This is pretty cool. I'm guessing the reason it's not supported directly in Angular is because of the dependency chain. If module A depends on module B, and module B lazy loads some of its services then you have a problem.
But if you understand that inherent pitfall then this could really come in handy.
I hacked up an experiment using $rootScope. Not better, just different.
http://ng.malsup.com/#!/lazy-experiment
@Mike,
Cool site! Is ng-nuggets yours? Looks like a great collection of information that I'll be digging through!
@Ben,
Yep, ng-nuggets is just a place where I store my Angular notes. I find I remember things better when I write them down.
@Mike - very cool. I'll be leaving that open in a tab :)
Hi Ben,
I just tried the above demo page with AngularJS version 1.3.0 beta 13, and I get this error:
Error: [$compile:multidir] Multiple directives [ngSwitchWhen, ngInclude] asking for transclusion on: <div ng-switch-when="before" ng-include=" 'before.htm' ">
I'm new to AngularJS, so I have no idea yet where to look for a fix or whatever. I thought I would give you a heads-up that something might have changed.
Like you, I'm very interested in how AngularJS can be made to load additional code and pages, so I found your post a perfect starting point. I'll post back if I do happen across a fix.
Very good!!!
Thank you for your code. It helped me solve my problem. What I was facing was that I needed to dynamically add dependencies after bootstrapping. The problem was that they were creating the directives I needed on their own modules. Using your solution, plus overriding the angular.module function, I finally got it.
Here's my solution:
http://pinkieguy.com/post/101949656975/loading-module-dependencies-in-angular-after-bootstrap
One more awesome blog (y) . Although, It was very difficult to reach this blog from google. Google was not showing this blog. But I made it to reach here.
I have a query regarding the blog:
Why you are storing controller native method in _controller variable?? although we are not using it?
app._controller = app.controller;
Please let me know, if I have missing something in your blog regarding this..
Hi Ben, you're a life savior! Thank you.
This is a very cool hack. I've followed IFY article and your example and you saved my life on how to load this modules!
Many thanks!!