Web Compression: Minifying CSS & JS

Why CSS/JS/etc. should be minified, and how the process of "minification" works.

Web Compression: Code Minification

Introduction

Website Compression: Why CSS and JS Minifying is important

Have you ever wondered how styling and client-side code is compressed? One way to accomplish this is with minification. The term is derived from the word minimizing; it is a small description into what the process actually is. Minimizing is essentially the process of removing unused/unnecessary spacing or control characters (i.e. line breaks) to save on the data required for a transfer. The best part about minification is that it can be done to virtually any web language: from CSS (Cascading Style Sheets), to HTML (Hyper Text Markup Language) and JS (JavaScript), minification can offer a noticeable performance boost with larger files.

Example of Minifying

With the following page, the process of “minimizing” can be demonstrated:

index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Test Website</title>
        <script src=”test.js” type=”text/javascript”></script>
    </head>
    <body>
        <h1>Hello, world!</title>
        <p>If JavaScript is working, <span id=”flag”>I’ll be changed!</span></p>
    </body>
</html>

The test.js specified in the HTML <head> block:

function test() { 
    document.getElementById("flag").innerText = “then we’ll be having a great day!”;
}

if (document.readyState == “complete”) {
    test();
}

First, we’ll begin by minifying our index.html page:

<!DOCTYPE html><html><head><title>Test Website</title><script src=”test.js” type=”text/javascript”></script></head><body><h1>Hello, world!</title><p>If JavaScript is working, <span id=”flag”>I’ll be changed!</span></p></body></html>

Notice how all unnecessary spacing has been removed, while spaces within our paragraph block have been preserved (we cannot “remove” these spaces, otherwise the page would be rendered differently).

Finally, with our test.js file:

function test(){document.getElementById("flag").innerText=“then we’ll be having a great day!”} if(document.readyState==“complete”){test()}

The difference here is (obviously) not large, but, with unnecessary spacing and control characters removed on a JS file of, say, 10K lines, there could be a potential savings of hundreds of kilobytes (which is a free boost of load performance without needing to optimize each line of code manually).

Did you find this article helpful?

0 out of 0 Bunnies found this article helpful

Glossary

Compression

A type of algorithm used to make files smaller.

Minification

The act of minimizing the amount of unnecessary whitespace transferred between a server and client.

Prove your Knowledge.
Earn a bunny diploma.

Test your knowledge in our Junior and Master Quizes to see where you stand. Prove your mastery by getting A+ and recieving a diploma.

Start the QuizBunny with a diploma.