简体   繁体   中英

AngularJS reducing HTTP request by combining javascript files

Using angularJS is great. Although i see a problem in that i have the following files:

  • app.js
  • controllers.js
  • filters.js
  • directives.js
  • services.js

That along with the actually AngularJS library files and perhaps jQuery is allot of http requests to the server.

Is there a way to combine all these together for a production environment? More to the point is there a specific AngularJS recommended way to do this?

The Grunt.js project is able to execute tasked commands such as minification and concatenation as I described above. The two grunt.js plugins with the widest support for these tasks are:

  • Uglify (minification)
  • Concat (file concatenation)

below is a sample task script for these:

module.exports = function(grunt) {

  grunt.initConfig({
    concat: {
      options: {
        separator: ';'
      },
      dist: {
        src: ['assets/**/*.js'],
        dest: 'assets/js/<%= pkg.name %>.js'
      }
    },
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
      },
      dist: {
        files: {
          'assets/js/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
        }
      }
    },
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-concat');

  grunt.registerTask('default', ['concat', 'uglify']);

};

I dont usually answer my onw questions although i believe that relying on a server to compile, cache and check cached versions is not the way to go. Unnecessary processors and systems to maintain on a production environment.

Combining and minification of script is mostly done on server. Different technologies\\tools provide different mechanism to support this feature. I dont think it is a AngularJS concern.

The only thing you need to take care if using minification is dependency injection can break in Angular. So this form of DI would be preferred.

app.controller('myController',['dependency1',
    function(dependency1) {
    }
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM