Minification
As web applications increase in complexity, they also increase in size. They contain more HTML, more CSS, more images, and more JavaScript. To provide some context, the uncompressed development version of the popular JavaScript library, jQuery (v1.9.1), has reached a whopping 292 KB. With the shift to mobile, our users are often on unreliable connections and loading this uncompressed jQuery file could easily take more than 5 seconds. This is only one file, however, often websites can be as large as 2-3MB causing load times to skyrocket. A blog post from KISSmetrics (http://gswg.io#loading-time-study) reveals the following, using data from gomez.com and akamai.com:
73% of mobile Internet users say they have encountered a website that was too slow to load.
51% of mobile Internet users say they have encountered a website that crashed, froze, or received an error.
38% of mobile Internet users say they have encountered a website that wasn't available.
47% of consumers expect a web page to load in 2 seconds or less.
40% of people abandon a website that takes more than 3 seconds to load.
A 1 second delay in page response can result in a 7% reduction in conversions.
If an e-commerce site is making $100,000 per day, a 1 second page delay could potentially cost you $2.5 million in lost sales every year.
Based on this information, it is clear we should do all we can to reduce page load times. However, manually minifying all of our assets is time consuming, so it is Grunt to the rescue! The Grunt team has plugins for the following common tasks:
Minify JavaScript—http://gswg.io#grunt-contrib-uglify
Minify CSS—http://gswg.io#grunt-contrib-cssmin
Minify HTML—http://gswg.io#grunt-contrib-htmlmin
In the following example Gruntfile.js
, we see how easy this process is. Much like the compilation tasks above, these minification tasks are also a transformation, in that they have file inputs and file outputs. In this example, we'll utilize the grunt-contrib-uglify
plugin, which will provide the uglify
task:
grunt.initConfig({ uglify: { target1: { src: 'foo.js', dest: 'foo.min.js' } } });
This is only a portion of Code example 01-minify
, the complete snippet can be found in the code examples (http://gswg.io#examples) or by returning to the start of this chapter. As with the uglify
task, the cssmin
and htmlmin
tasks also have options to customize the way our code is compressed. See the corresponding GitHub project pages for more information.
Tip
If you're using Jade to construct your HTML, then you can use its built-in compression option by setting pretty
to false
.