Search code examples
javascripthttpangularjsgruntjsbundling-and-minification

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?


Solution

  • 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.