如何加载angularjs脚本文件
How to load angularjs scripts files
我有一个angularjs应用程序,其中有一堆控制器、服务和指令。让我说它们是controller.js
、service.js
和directive.js
,但事实是js文件比三个多得多。为了减少http请求,我将这些js文件合并为一个文件,假设它是app.js
。所以我的index.html看起来像
<html lang="en">
<body>
<div data-ng-view></div>
<script src="app.js"></script>
</body>
</html>
但是,在我的开发环境中,我希望调试分离的文件,而不是组合的文件。修改后的index.html提供了这种功能。
<html lang="en">
<body>
<div data-ng-view></div>
<script src="controller.js"></script>
<script src="service.js"></script>
<script src="directive.js"></script>
</body>
</html>
然而,我不想更改index.html。是否可以定义类似的内容:
require('controller.js');
require('service.js');
require('directive.js');
在我的CCD_ 5中。我已经做了一些搜索,结果显示有一种将angularjs和requirejs一起使用的方法,然而,它需要我以requirejs的方式重新定义我的控制器和服务。就我而言,这需要付出很多努力。而且,我不需要实现动态加载,因为在生产环境中,只需要下载一个javascript文件。
一个非常好的解决方案是使用源映射。因此,即使您有一个文件,浏览器也知道初始文件!阅读更多html5rocks。
此外,我强烈建议您对这类工作使用javascript任务运行器/构建系统,如grunt或gullow。
使用gull连接和创建源映射非常简单:
var gulp = require('gulp');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('javascript', function() {
return gulp.src('src/**/*.js')
.pipe(sourcemaps.init())
.pipe(concat('all.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('dist'));
});
第二个选项是这个插件gulp预处理,您可以在其中设置不同的env变量,比如dev、production。根据任务负载的不同,可以是串联的文件,也可以是每个单独的文件。
很抱歉提供基于外部插件的解决方案,但我认为它们可以为您节省很多时间!
如果你想在测试和调试时将文件分开,但在生产时将它们合并,我建议使用Grunt.js或我个人最喜欢的Gulp.js这样的构建系统。使用这些自动化构建工具,你可以让它创建一个任务,并对JS文件进行篡改,生成允许开发工具引用原始文件的映射。这可以为您的工作流程创造奇迹。这确实需要Node.js,所以您也必须安装它。这仍然是一项艰巨的工作,但我认为这比重写所有代码要好。
您的特定案例的示例构建文件可能如下所示:
//this(my-js) will grab all js file in the js directory, combine, minify, mangle,
//rename and create sourcemaps. it also has a dependency(js-libs) to handle
//your libraries first.
gulp.task('my-js', ['js-libs'], function() {
return gulp.src([
'src/js/*.js',
])
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(concat('app.min.js'))
.pipe(uglify())
.pipe(sourcemaps.write('maps'))
.pipe(gulp.dest('build/js'));
});
//this task will run the js task and then start a task that watches the files for
//changes and reruns the my-js task anytime something changes
gulp.task('default', ['my-js'], function () {
gulp.watch('src/js/*.js', ['my-js']);
});
这只是我脑海中浮现的一个例子。未测试。一旦es6问世,我们就可以访问import 'somefile'
。此外,请记住,当http/2完全实现时,我们将进行多路复用,这将允许在单个连接中进行多个文件请求:https://http2.github.io/faq/#why-is-http2-多路复用
- 动态添加AngularJS脚本
- AngularJS:如何使用java脚本函数更改跨度的ng-show条件
- 从不同的脚本调用Post AngularJs
- angularjs脚本没有输出
- 调用AngularJS内部<脚本>标签
- 更改Angularjs路线时,演示文稿脚本的放置位置
- 在AngularJs中动态地将url添加到脚本标记中
- AngularJS - 在所有指令呈现后包含<脚本>
- 使用 Angularjs 加载 JavaScript 脚本的最佳方法是什么?
- AngularJS UI 路由器:包含控制器脚本的位置
- AngularJS:如何在指令中使用JS脚本
- 重写我的 angularJS 脚本以支持 localStorage
- 在AngularJS脚本中使用$scope变量
- 最小化包含自定义过滤器的AngularJS脚本
- 如何加载angularjs脚本文件
- 获取AngularJS脚本中的HTML元素数据
- AngularJS脚本在赋值时给出了左边无效的ReferenceError错误
- 在页面中包含angularjs脚本的正确方法
- AngularJS脚本运行了两次
- 为什么Closure Compiler会破坏这个AngularJS脚本?