0

模块化编程能否有助于降低加载时​​间?如何?

我读到了模块化 AngularJS 应用程序的方法。一般来说,这样做的原因是在创建大型应用程序时具有良好的结构,这样就不必在文件之间滚动太多,并且在可重用模块和独立模块之间进行分离。

虽然从实际的角度来看这绝对是有道理的,但我几乎找不到支持加载时间的论点?


引用单独的 .html 文件中的 .js 文件而不是 index.html 中的所有文件会减少加载时间吗?

我在想以下几点;如果您的目录结构如下(目录结构示例)。如果您将.js引用包含在单个.html文件中而不是全部在index.html. 例如,在sidebarView.html 你会添加:

<script src='sidebarDirective.js'></script>

目录结构示例

app/
----- shared/   // acts as reusable components or partials of our site
---------- sidebar/
--------------- sidebarDirective.js
--------------- sidebarView.html
---------- article/
--------------- articleDirective.js
--------------- articleView.html
----- components/   // each component is treated as a mini Angular app
---------- home/
--------------- homeController.js
--------------- homeService.js
--------------- homeView.html
---------- blog/
--------------- blogController.js
--------------- blogService.js
--------------- blogView.html
----- app.module.js
----- app.routes.js
assets/
----- img/      // Images and icons for your app
----- css/      // All styles and style related files (SCSS or LESS files)
----- js/       // JavaScript files written for your app that are not for angular
----- libs/     // Third-party libraries such as jQuery, Moment, Underscore, etc.
index.html
4

1 回答 1

4

当您使用 Angularjs 构建单页应用程序时,最佳实践是将所有 javascript 连接并缩小到一个文件中,并将所有 html 视图预编译到一个文件中。然后,您可以将它们直接包含到您的 index.html 文件中。这意味着客户端只需发出两个网络请求即可获取应用程序运行所需的所有代码,并且在切换视图时无需等待下载内容。

就个人而言,我gulp用来构建我的文件,但是有很多不同的构建系统。这是我的 gulpfile 中处理脚本构建的示例:

gulp.task('scripts', function() {
  return gulp.src(scripts)
    .pipe(concat('app.js'))
    .pipe(gulp.dest('./build/scripts'))
    .pipe(refresh(lrserver));
});

gulp.task('customscripts', function() {
  return gulp.src(customscripts)
    .pipe(concat('app-custom.js'))
    .pipe(gulp.dest('./build/scripts'))
    .pipe(refresh(lrserver));
});

gulp.task('views', function() {
  return gulp.src(views)
    .pipe(minifyhtml({empty:true, spare: true, quotes: true, conditionals: true}))
    .pipe(rename(function(path) {
      path.dirname = '';
    }))    
    .pipe(html2js({moduleName: 'app', prefix: 'views/'}))
    .pipe(concat('app-views.js'))
    .pipe(gulp.dest('./build/scripts'))
    .pipe(refresh(lrserver));
});

然后在 index.html 文件中:

<script src="/scripts/app-custom.js"></script>
<script src="/scripts/app.js"></script>
<script src="/scripts/app-views.js"></script>

如您所见,目录结构在一天结束时根本不重要。我个人转而使用模块化方法,发现对于大型项目,保持组织和组件化要容易得多。

于 2014-12-19T09:37:31.043 回答