javascript - AngularJS 应用程序的引导/初始化流程

标签 javascript angularjs html execution

我想知道 AngularJS 应用程序的初始化流程是否可以根据 HTML 文档中不同 block 的执行顺序进行预测。

我读了这个问题What is meant by Bootstrapping in angular JS? ,它解释了很多过程,但没有详细回答我的问题。

我有一个 plunker 示例 http://plnkr.co/edit/boVFjHWoxdbiADq41dXC?p=preview ,其中我 console.log() 数字,按照我认为它们会执行的顺序。但有点令人惊讶的是 .run() block 的执行似乎被推迟了。

<!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>

所以我有几个问题:

  1. 可以肯定地说,在控制台中用数字“2”标记的 run() block 将始终在处理完页面的其余部分后执行吗?
  2. 我知道启动 .run() block 执行的是调用 angularInit(),它是通过在 DOM 就绪时调用 read() 来执行的。这是正确的吗?
  3. 这是否意味着,实际上 run() block 的执行发生在同一时间点上,就像它被分配给 window.onload 一样?

最佳答案

实际上有关于 https://github.com/angular/angular.js/blob/ce669edfa14dc7eb7c389d2f82c9c98399a9009b/docs/content/guide/module.ngdoc 上的运行 block 的文档

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.

angularInit 函数初始化模块,然后调用它们自己的运行 block 。这发生在 src/angular.suffix

  jqLite(document).ready(function() {
    angularInit(document, bootstrap);
  });

因此 run 函数总是在文档加载后被调用。 由于 Angular 将开始初始化,因此 window.load 和初始化之间可能会有一些时间。

关于javascript - AngularJS 应用程序的引导/初始化流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29699751/

相关文章:

javascript - Nodejs 按需导出功能

android - 用于 Firefox 和 Chrome 的 MPEG 4 Visual 的 <video> 标签

javascript - 网页 : detect and block certain keyboard shortcuts

javascript - 错误: [$injector:unpr] Unknown provider: $cordovaSmsProvider <- $cordovaSms <- smsController

html - 为什么我的页面让我在移动设备上滚动两次?

javascript - 在不使用滚动条时让 WOW.js 和 fullPage.js 协同工作?

javascript - Angular 和 Karma - 为什么这个测试失败?

javascript - 允许用户继续使用终端的终端应用程序

javascript - 在另一个 Ajax 请求中处理多个 Ajax 请求

angularjs - 在 AngularJS 中限制 PubNub 请求