Delaying AngularJS App Initialization

There may be situations where you would like to delay the initialization of your AngularJS app until after some asynchronous operation has finished.  This has come up for different reasons on a couple recent projects that I’ve worked on.  In one case, some initialization parameters for the app’s $routeProvider needed to be retrieved when the page loaded.  In another, we had to complete some session initialization before loading the app.  Being able to control the initialization-time of your application can be a valuable tool for complex applications.


Essentially, you want to have something like this:


How To:

  1. Prevent the application from initializing itself at load time by removing the ng-app directive from the DOM.
  2. Explicitly instruct AngularJS to load the application when desired using:

    angular.boostrap(dom-element, [‘myApp’]);

    This function can take any jQuery/Angular-wrapped element as well as the name of the module to initialize.  Note that this module and its dependencies must have already been loaded before the call to angular.bootstrap() as controllers, directives, services, etc. cannot be added to an application after it is bootstrapped.

For more on manual vs. automatic bootstrapping, checkout the Angular docs on application bootstrapping.

It's only fair to share...
Share on Facebook
Tweet about this on Twitter
Share on LinkedIn