Back

JavaScript minification

What is a JavaScript minification ?

Minification is the removal of unnecessary characters from a file in order to reduce its size, so it compacts the instructions. These useless characters are, for example, comments, spaces and tabs.

In JavaScript the names of the variables have no importance for the interpretation of the script by the browser, so they can be reduced (var variable = ... becomes var a = ... ). In the same way, the useless code can be removed (variable declared in a function and not used).

Why is this important ?  

Removing unnecessary characters and compacting the code improves the loading time because the JavaScript file weighs less. 

How to perform a JavaScript minification 

To carry out this treatment, it is interesting to use a tool (and not to do it manually) such as javascript-minifier.com, which allows you to minimize a JavaScript script online.

Example of a script before minification :

function myFirstFuction(parameter) {
    var maVariable = "minification 1";
}

function mySecondFunction(parameter) { 
    console.log(parameter);
}

After minification :

function  myFirstFunction(n){}function mySecondFunction(n){console.log(n)}

It is also possible to include external scripts in their minimized version. Many vendors (CDN) offer this for the production version.