Book Image

Getting Started with Grunt: The JavaScript Task Runner

By : Jaime Pillora, Bocoup LLC
Book Image

Getting Started with Grunt: The JavaScript Task Runner

By: Jaime Pillora, Bocoup LLC

Overview of this book

Table of Contents (12 chapters)

Concatenation


As with minification, concatenation (or joining) also helps reduce page load time. As per the HTTP 1.1 specification, browsers can only request two files at once (see HTTP 1.1 Pipelining). Although newer browsers have broken this rule and will attempt to load up to six files at once, we will see it is still the cause of slower page load times.

For example, if we open Chrome Developer Tools inside Google Chrome, view the Network tab, then visit the cnn.com website, we see approximately 120 file requests, 40 of which are loading from the cnn.com domain. Hence, even with six files being loaded at once, our browsers still must wait until a slot opens up before they can start downloading the next set of files.

Also, if there are more files to load over a longer period of time, there will be a higher chance of TCP connection dropouts, resulting in even longer waits. This is due to the browser being forced to re-establish a connection with the server.

When building a large Web Application, JavaScript will be used heavily. Often, without the use of concatenation, developers decide not to segregate their code into discrete modular files, as they would then be required to enter a corresponding script tag in the HTML. If we know all of our files will be joined at build-time, we will be more liberal with creation of new files, which in turn will guide us toward a more logical separation of application scope.

Therefore, by concatenating assets of similar type together, we can reduce our asset count, thereby increasing our browser's asset loading capability.

Although concatenation was solved decades ago with the Unix command: cat, we won't use cat in this example, instead, we'll use the Grunt plugin: http://gswg.io#grunt-contrib-concat. This example Gruntfile.js file demonstrates use of the concat task, which we'll see is very similar to the tasks above as it is also a fairly simple transformation:

//Code example 08-concatenate
module.exports = function(grunt) {

  // Load the plugin that provides the "concat" task.
  grunt.loadNpmTasks('grunt-contrib-concat');

  // Project configuration.
  grunt.initConfig({
    concat: {
      target1: {
        files: {
          "build/abc.js": ["src/a.js", "src/b.js", "src/c.js"]
        }
      }
    }
  });

  // Define the default task
  grunt.registerTask('default', ['concat']);
};

As usual, we will run it with grunt and should see the following:

$ grunt
Running "concat:target1" (concat) task
File "build/abc.js" created.

Done, without errors.

Just like that, our three source files have been combined into one, in the order we specified.