javascript - 加载 angularJS 的正确方法

标签 javascript html angularjs performance

就性能最佳实践而言,建议在页面底部加载 JavaScript。 AngularJS official documentation对于 Angular 应用程序也有同样的规定。

Place the script tag at the bottom of the page. Placing script tags at the end of the page improves app load time because the HTML loading is not blocked by loading of the angular.js script.

我的网页充满了 Angular Directive(指令)和 Angular 绑定(bind),并且我的 body 标记内没有任何静态 html 内容。一般建议还适用于我的网站吗?我希望此建议仅适用于具有静态内容和部分 AngularJS 内容的网站。

如果我将 Angular 放在底部,我假设首先将加载我的 html,然后进行 Angular 解析,然后再次进行 html 加载、解析和脚本执行。这是真的吗?如果我将 Angular 放在页面顶部,我可以获得一些性能优势还是性能会变差?

我已将所有脚本组合并缩小为一个。我没有任何外部模板。我有带有一些数据投标的内联模板。你也可以假设我使用 ng-cloak 和 debugInfoEnabled false。

我的应用程序看起来像

<!DOCTYPE html>
<html ng-app="coreModule">
<head>
    <title>Angular App</title>
    <link rel="stylesheet" type="text/css" href="app.css">
</head>
<body>
<directive1></directive1>
<directive2></directive2>
..
<directive10000></directive10000>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>

我需要按以下方式使用吗?

<!DOCTYPE html>
<html ng-app="coreModule">
<head>
    <title>Angular App</title>
    <link rel="stylesheet" type="text/css" href="app.css">
    <script type="text/javascript" src="angular.js"></script>
    <script type="text/javascript" src="app.js"></script>
</head>
<body>
<directive1></directive1>
<directive2></directive2>
..
<directive10000></directive10000>
</body>
</html>

最佳答案

如果 HTML 文件中除了 htmlheader 标记以及空的 body< 之外没有任何任何内容 那么你可能做错了。这就是原因。

在这种情况下,是否放置 script 标记并不重要,当您希望在 JS 加载之前显示内容时,这很重要,但在您的情况下没有内容可显示,因此如果 JS 下载很慢,那么将显示一个空白页面。不确定您的应用程序是公共(public)应用程序还是私有(private)应用程序。如果是后者,这种状态可以接受,但如果它要公开,那么我不推荐这种情况。

您应该在初始页面加载中放置一些内容,然后,这些内容会得到改进或被 Angular 替换。

加载 Angular 的提示

您应该将所有脚本连接成一个脚本并将其缩小,以便在加载网站时节省一些带宽。

您还应该编译所有模板并将它们放入带有 $templateCache 的脚本中,如下所示:

$templateCache.put('main.html', '<strong>Main</strong> template'); 

这样,Angular 就不会向您的服务器发出任何额外的请求来尝试获取模板。您可能需要检查一下相关的 grunt 和 gulp 任务。

此外,在生产中您可能希望使用以下方法禁用调试数据:

myApp.config(['$compileProvider', function ($compileProvider) {
  $compileProvider.debugInfoEnabled(false);
}]);

因为 Angular 会更快。

关于javascript - 加载 angularJS 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31045161/

相关文章:

javascript - 从哪里开始:JavaScript,NodeJS-加上Universe

Javascript 在点击事件时显示 for 循环中点击的项目

javascript - 以编程方式运行时未找到 Node 依赖项

javascript - NodeJS : Send HTTPS request but get HTTP

javascript - 按钮 "Q"和 "F2"的 key 代码相同

javascript - 单击按钮后无法读取刚刚在 JS 中创建的 DIV 的属性 ("null")

html - 可以在 input[type=range] 中指定不均匀的步骤吗?

javascript - 用空值替换选项

html - 表格列没有从中心分开

javascript - 在运行时动态分配 ng-controller