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:
- Is it safe to say that the run() block, flagged in the console by the number "2", will always be executed after the rest of the page was processed?
- I get that what initiates the execution of the .run() block is the call angularInit(), which is executed by the call ready() on DOM ready. Is that correct?
- Does that mean that, in effect, the execution of the run() block happens on the same tick, as it would if it was assigned to window.onload?