I would like to know if the initialization flow of AngularJS apps is predictable in terms of the order of execution of different blocks within an HTML document.
I read this question What is meant by Bootstrapping in angular JS?, which explains a lot of the process, but does not answer my question in detail.
I have a plunker example http://plnkr.co/edit/boVFjHWoxdbiADq41dXC?p=preview, where I console.log() numbers, in the order that I thought they would execute. What was a bit surprising though was that the execution of the .run() block seems to be deferred.
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js@1.4.0-rc.0" data-semver="1.4.0-rc.0" src="https://code.angularjs.org/1.4.0-rc.0/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<!--<script src="script.js"></script>-->
<script>
// Code goes here
console.log(1);
angular.module('app', [])
.run(function () {
console.log(2);
setTimeout(function () {
console.log(6);
});
});
</script>
<script>
console.log(3);
</script>
</head>
<body>
<img src="http://www.mrwallpaper.com/wallpapers/Sicily-Italy.jpg" />
<script>
setTimeout(function () {
console.log(5);
})
</script>
<img src="http://www.wishsicily.com/gallery/1370_scicli-ragusa.jpg" />
<script>
console.log(4);
</script>
<h1>Hello Plunker!</h1>
</body>
</html>
So I have a few questions:
There is actually documentation about the run block on https://github.com/angular/angular.js/blob/ce669edfa14dc7eb7c389d2f82c9c98399a9009b/docs/content/guide/module.ngdoc
Run Blocks
Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
The angularInit function initializes the modules which then call their own runblocks. That happens in src/angular.suffix
jqLite(document).ready(function() {
angularInit(document, bootstrap);
});
So the run function will always be called after the document loaded. Since Angular will start initializing then, there may be some time between the window.load and the initializing.