Skip to content

Instantly share code, notes, and snippets.

@jberndsen
Created November 4, 2017 11:44
Show Gist options
  • Save jberndsen/e32b411396e43c47cb30a042911b4ae9 to your computer and use it in GitHub Desktop.
Save jberndsen/e32b411396e43c47cb30a042911b4ae9 to your computer and use it in GitHub Desktop.
Run AngularJS initialization logic before main AngularJS app
// define the module of the bootstrap app
var bootstrapModule = angular.module('bootstrapModule', []);
// the bootstrap service loads the config and bootstraps the specified app
bootstrapModule.factory('bootstrapper', function ($q, $http) {
return {
bootstrap: function (appName) {
var deferred = $q.defer();
// do initial loading here
// in our case, this means doing any pre-init async http requests
$q.all([$http.get('resources/test-a.json'), $http.get('/test-b.json')])
.then(function (results) {
// when they're all loaded, start expanding our actual application
var app = angular.module(appName);
// declare app factories/constants/etc. that required pre-init here
// in our case, using a constant is the least invasive method to retain
// current functionality.
app.constant('TestAResponse', results[0]);
app.constant('TestBResponse', results[1]);
// we can now bootstrap the actual application.
angular.bootstrap(document, [appName]);
deferred.resolve();
});
return deferred.promise;
}
};
});
// Create a div which is used as the root of the bootstrap app
// in the run() function you can now use the bootstrapper service
// and shutdown the bootstrapping app after initialization of the actual app
var appContainer = document.createElement('div');
bootstrapModule.run(function (bootstrapper) {
bootstrapper.bootstrap('app').then(function () {
// removing the container will destroy the bootstrap app
try {
appContainer.remove();
} catch (e) {
}
});
});
// make sure the DOM is fully loaded before bootstrapping
angular.element(document).ready(function () {
angular.bootstrap(appContainer, ['bootstrapModule']);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment