【问题标题】:precompile angular js template to speed up application startup预编译 Angular js 模板以加速应用程序启动
【发布时间】:2014-02-06 09:58:54
【问题描述】:

我有一个很大的 Angular 应用程序,在主页中包含 5 个模板,使用

 <script type="text/ng-template" id="/myMainTemplate.html">...</script>
 <script type="text/ng-template" id="/myTemplatePage2.html">...</script>
 <script type="text/ng-template" id="/myTemplatePage3.html">...</script>
 <script type="text/ng-template" id="/myTemplatePage4.html">...</script>

但是,我的应用程序需要很长时间才能启动。

删除模板 2/3/4 修复它,但当然破坏了应用程序,我的猜测是 angularjs 编译 5 个模板需要太多时间。

有没有办法预编译 angularjs 模板,例如使用 nodejs 或类似的东西(也许我们可以用把手编译模板的方法相同)?

如果我很好理解 $compile 指令,我的想法是将指令 $compile(myTemplate) 移动到客户端内部的服务器端

【问题讨论】:

    标签: javascript angularjs templates precompile


    【解决方案1】:

    看看 grunt-html2js 任务。

    https://github.com/karlgoldstein/grunt-html2js

    它将普通的 Angular HTML 模板转换为 JavaScript,以便连接到您的主应用程序包中。一旦模板在您的应用程序包中,它们就会在 Angular 的模板缓存中准备好,以便它们立即加载。

    【讨论】:

    • 不幸的是,它不会将它们转换为 JavaScript 函数,而是转换为字符串。 $compile 仍然需要运行。这不是真正的 AOT。
    • 这是 2014 年的答案,老兄,AOT 编译当时还不是一件事:)
    • 我知道。我仍然希望 AOT 现在可以在 Angular JS 中使用。
    【解决方案2】:

    看来我错了,需要时间的不是编译模板。浏览器加载所有页面的速度很慢,基本上 document.ready 事件需要一些时间才能触发。

    为了解决这个问题,我只在页面中包含了我的主模板 &lt;script type="text/ng-template" id="/myMainTemplate.html"&gt;...&lt;/script&gt;,并使用异步 $http 调用加载其他模板,基于此解决方案:https://gist.github.com/vojtajina/3354046

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 1970-01-01
      • 2017-09-11
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多