How to Minify JavaScript & CSS?  

As a frontend developer, your job is to create beautiful websites and a website that runs smoother and loads quicker. Creating such a visually stunning and smooth-loading webpage, on the other hand, is not that simple. However, there is one principle that will assist you in improving the performance of your project.

Known as ‘minify’ or ‘minification,’ minifying is the process of minimizing the unnecessary characteristics in the source code. The unnecessary features refer to whitespaces, line breaks, comments, and block delimiters.

Adding these characters to the code allows developers to interpret what the code is about and makes the code more understandable for us humans so that we can quickly rectify any problems in the source code.

But these characters are the same characters that contribute to the slow loading of the web pages. So to avoid the instance of web pages loading slower, programmers minify their codes.

Files containing codes made of frontend programming languages such as HTML, CSS, and JavaScript are the ones that are minified so that the browser can read the codes faster.

Now let’s look into how and why we need to minify JavaScript and CSS code in detail.

Why Minify JavaScript?

Minification in JavaScript is the process of eliminating any characters from the source code that aren’t required. That’s why it’s called “minification”: all of the data that isn’t necessary for the JavaScript to work is deleted from the source code, resulting in a minimised version of JavaScript. Even when these characters are removed from the JavaScript source code, the JavaScript code’s functionality remains unchanged.

As a result, your JavaScript code will behave exactly the same even after the minification process. “Minified” code refers to code that has undergone the minification process.

What are the benefits and advantages of JavaScript minification?

The main goal of JavaScript minification is to reduce the time it takes for the JavaScript code to download or transfer from the server hosting the website’s JavaScript. Minification speeds up downloads by reducing the amount of data that must be downloaded. As there is less data, the user’s browser spends less time processing it, resulting in time savings. 

So, we can say that minification is conducted on JavaScript source code since it is fundamentally a performance optimisation minified JavaScript that causes websites to load faster.

Pros:

  • The file size is smaller, and the download speed is faster.
  • It’s harder to imitate your work.

Cons:

  • An extra build setup is needed.
  • A build process can be slower.
  • Harder to debug, you have to use source maps.
  • Minification isn’t allowed if you’re going to publish a browser extension.

How to Minify JavaScript?

You’ll need the help of a few tools to minify JavaScript code. The majority of the tools for minifying JavaScript can be available on the internet. The following are some of our suggestions:

The tools mentioned of our some of the top choices when it comes to minifying JS code. 

Now comes the next question, how do you minify JavaScript?

The steps to minify JavaScript are straightforward and may be done with any tool:

  • Upload the source code file or paste your source code.
  • Set the parameters for a particular output.
  • To minify or compress the code, click the button.
  • Copy the minified code output or download the minified code file once the procedure is finished.

Example: Original Code

Now let’s look into how minifying a code works using the following example:

function myFunction(myNumber){
     var myArray = new Array(myNumber);
     var myObject = new Object();
     var myArray2 = new Array();
     for(var myCounter = 0 ; myCounter < myArray.length ; myCounter++){
         myArray2.push(myCounter);
         var myString = myCounter.toString()
         myObject[ myString ] = ( myCounter + 1 ).toString();
     }
    var myContainer = new Array();
    myContainer[0] = myArray2;
    myContainer[1] = myObject;
    return myContainer;
}

The above code is copied to a minifier tool. After minifying, the output will be as follows:

After Minification:

function myFunction(r){
 for(var n=new Array(r),t=new Object,e=new Array,a=0;a<n.length;a++){
  e.push(a);
  var o=a.toString();
  t[o]=(a+1).toString()
 }
 var i=new Array;
 return i[0]=e,i[1]=t,i
}

In terms of functionality, both codes are similar. The main difference is that you can get a gist of what the code is about; however, in the minified version, you probably won’t know what it’s attempting to do.

Try out both codes, and you will see a difference in speed.

Another advantage of minifying code is that the minified version is hard to comprehend. So the security of your program will be preserved.

Why Minify CSS?

Minifying a CSS file entails removing extraneous characters from the source code in order to minimise file size and speed up site loading. The minified version of a webpage is transmitted instead of the full version when a user requests it, resulting in faster response times and lower bandwidth costs. It increases the site’s speed and accessibility while also assisting in the improvement of search engine rankings.

To be more precise, CSS minification reduces page load time in two ways. 

  1. As there is less information to deal with, smaller files take less time and resources to fetch and compress at the origin server, send to the client, and finally download by the browser.
  1. The second explanation has to do with how web pages are displayed in browsers. After downloading a web page, the browser parses the HTML file from top to bottom before displaying it. When the browser run into a link to an external CSS file, it suspends HTML parsing so that the external CSS code can be processed. Users will not see any page content until the browser has digested all related CSS. As a result, CSS is referred to as a “render blocking” resource.

Minification is now standard practice on websites and web applications for a straightforward reason: it speeds them up. The underlying premise is straightforward: the less code there is to parse, the faster the web page loads.

The characters that are eliminated during minification are:

  • White spaces
  • Line breaks 
  • Comments
  • Block delimiters

The ‘.min.CSS’ extension indicates that the CSS files have been minified.

Is CSS code minification requisite?

This isn’t a significant concern if the web page is simple and there’s only a tiny amount of CSS. Visitors may notice a delay in loading time if the CSS files are enormous. That’s why, especially if your site is aesthetically complex and requires a lot of CSS, reducing CSS file sizes via minification is recommended. 

Visitors will spend minimal time waiting for the webpage because there will be fewer render-blocking resources to parse.

CSS minification is unlikely to make your website lightning fast right away. Still, from 1 second to 3 seconds of load time, the chance of a bounce jumps by 32%; thus, even a tiny performance boost makes a difference. 

Plus, without changing the content of your page, quicker pages improve usability for mobile visitors and contribute considerably to your search engine rating. So, if you weren’t already convinced, hopefully, you are now.

Pros:

  • Unnecessary parameters are extracted, leaving less to be sent to the client.
  • Less data could imply fewer metadata and client-server roundtrips.
  • Shorter loading times.
  • All of this results in a positive user experience and a better ranking impact.

Cons: 

  • Other optimisations have a much more significant impact than minifying HTML, CSS, and JS files like optimising images, fonts etc.
  • When code is minified, it becomes incomprehensible to humans, making additional adjustments nearly impossible. As a result, maintain your original full-sized, well-organised sources.

How to Minify CSS?

CSS codes can be minified with the help of online tools or using several codes. Here are some of the online tools which are recommended for minifying CSS codes:

  • CSSnano
  • CSSO
  • UNCSS

You can follow the following steps to minify the code using the above resources.

  • Copy the source code or the file and paste it or upload it.
  • Some programmes allow you to customise the code for a specific result.
  • To minify or compress the code, click the minify button.
  • Download the output of the minified code or save the minified code file.

Now let’s look into an example of how to minify a CSS code.

Example: Original Code

The following is the original CSS code. This code will be uploaded into the minifying tool.

/* heading elements */
body {
    color: #33475b
}
h1 {
    font-size: 2rem;
    font-weight: 700;
    line-height: 2.75rem
}
h2 {
    font-size: 1.625rem;
    font-weight: 700;
    line-height: 2.25rem
}
h3 {
    font-size: 1.5rem;
    font-weight: 500;
    line-height: 2.125rem
}
/* other elements */
p, span {
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.75rem
}
blockquote {
    font-size: 1.5rem;
    font-weight: 400;
    line-height: 2.375rem
}
ol, ul {
    list-style: none
}
table {
    border-collapse: collapse;
    border-spacing: 0
}
button {
    appearance: none;
    font: inherit;
    margin: 0
}

After Minification:

body{color:#33475b}h1{font-size:2rem;font-weight:700;line-height:2.75rem}h2{font-size:1.625rem;font-weight:700;line-height:2.25rem}h3{font-size:1.5rem;font-weight:500;line-height:2.125rem}p,span{font-size:1rem;font-weight:400;line-height:1.75rem}blockquote{font-size:1.5rem;font-weight:400;line-height:2.375rem}ol,ul{list-style:none}table{border-collapse:collapse;border-spacing:0}button{appearance:none;font:inherit;margin:0}

As we can see from comparing the before and after, the after is hard to comprehend and look too complex. But the, using the after code, your webpage will be loaded faster and perform smoother.

As previously said, there are two methods for minifying CSS codes: one is to use online tools, and the other is to download tools to the editor itself. The following code demonstrates this:

  • First, enter
CSS-minify npm
  • The next step will be installing the CSS minify tools to the editor using the following code.
npm install CSS-minify -g
  • The following command is used to minify a single file:
CSS-minify -f filename
  • The following command is used to minify all the belonging to one directory:
CSS-minify -d sourcedir

where the sourcedir is the name of the folder containing the CSS files.

FAQs

Since the Minified Version Performs Better, Why Don’t Developers Write Minified Code From the Start?

If you’re asking this question, you’re presumably a newbie who is still learning how to code.

Minification involves removing whitespaces, formatting, indentation, and other characteristics that we developers as humans use to understand the program. Imagine writing a program without spaces and getting an error during run time. The consequences will be dire as you will not know what, where, and why the error was caused.

But web performance is essential, so you write codes in a way you understand, and you will minify it in a version where the browser can read and run without qualms.

What Are Some of the Drawbacks of Minification?

Because of site-dependent variables like themes, plugins, and server environments, minification can disrupt sophisticated programs. Minification must also be done in conjunction with other performance optimisation techniques. 

It might not deliver significant benefits on its own. Minification can potentially lead to difficult-to-trace problems.

What Is the Difference Between Compression and Minification?

It’s easy to be confused between minification and compression because they both require compressing the code. But keep in mind that minification and compression are not synonymous.

Although the goals are similar, compression differs in that it uses compression schemes like gzip or brotli to reduce file size and adds an HTTP response header to inform the client that the file is compressed CSS.

Whitespaces and other insignificant pieces of the programme are removed during minification.

Conclusion

A developer should seek numerous approaches to improve the source code in order for the software to work smoothly. We hope you now understand what minification is and how it might help your website operate better.

Basic CSS and JavaScript for free

If you’re new to coding, then try our free 5 Day Coding Challenge, where you can learn the basics of HTMLCSS and JavaScript. Register now through the form below.

Relational Databases

Databases, in combination with a Database Management System (DBMS), allow persistent storage, easy administration, and safe manipulation of information and are therefore among the most important computer applications. Data in a database is structured according to one of the multiple sets of rules. Proposed in 1970 by E.F. Codd, the relational data model is the […]

Python Cheat Sheet

Python is one of the most popular programming languages. It currently takes first place both in the Tiobe index and the PYPL index and has been named Language of the Year in 2007, 2010, 2018, 2020, and 2021. This popularity stems both from Python’s versatility and ease of use. Python can be used for Web […]

Git Stash

Git Stash is a built-in command that temporarily stores all of the most recent modifications to the code. That is, the modifications are stored, and the code is reset to its previous state. Git is software that allows a group of developers to keep track of changes and alterations to a source code throughout the […]