Minification Of JavaScript

What is JavaScript Minification

JavaScript Minification is the process of reducing the size of JavaScript files. To reduce the size, the comments, extra white spaces, and new line characters are removed from the script and the variable names are replaced with shorter variable names. Minification process does not affect the functionalities of JavaScript code.

How to Minify JavaScript

There are several online tools available to minify the JavaScript. Just search the term ‘Minify JavaScript’ on the internet. You can use any of them. Let us check this by an example. In this example. I am using jcompress.com tool.

Below is my JavaScript function,

  1. function AddNumbers(number1, number2)  
  2. {  
  3.     var addition = number1 + number2;  
  4.     //Here we add two numbers  
  5.     alert('Addition is:' + addition)  
  6. }  
In this code there is one blank line and one comment. See what happens after minifying this code.
  1. function AddNumbers(d,i){var n=d+i;alert("Addition is:"+n)}  
The variables number1, number2 and addition are replaced with shorter names d, i and n. All white spaces, new lines and comments are removed from code.

Naming Convention for Minified JavaScript file

To differentiate minified files from original script files the word ‘min’ is used in the  file name, for example there are two files for JQuery; one is ‘jquery.js’ and another is ‘jquery.min.js’. The second one is the minified version.

Advantages of Minification
  1. As minification reduces the size of JS file it reduces the download time and the web page loads much faster.

  2. It reduces the bandwidth consumption of site.

  3. It improves the script execution time also.

  4. It reduces number of HTTP requests to server when combining many JavaScript files into one minified file, thus reducing the load on server and allowing more visitors to access web site.

Disadvantage of Minification

As white spaces and comments are removed, it is difficult to read and debug JavaScript file.

So, in development stage use non-minified JavaScript files. Just before deployment of application minify these files and deploy.

Conclusion

In this article we learned how minification helps to reduce the size of JavaScript file and increases the performance of web applications.

Read more articles on JavaScript:

Up Next
    Ebook Download
    View all
    Learn
    View all