Optimizing Your Website with Bootstrap: Minifying CSS and JavaScript

Once you have improved the MyPhoto style rules so that they’re as compact, efficient, and maintainable as possible, it is time to look into minification. Minification is the process of removing redundant characters from a file without altering the actual information contained within it. In other words, minifying our myphoto.css file will reduce its overall size, while leaving the actual CSS style rules intact. This is achieved by stripping out any whitespace characters within our file. Stripping out whitespace characters has the obvious result that our CSS is now practically unreadable and impossible to maintain. As such, minified style sheets should only be used when serving a page (that is, during production), and not during development.

Clearly, minifying your style sheet manually would be an incredibly time-consuming (and hence pointless) task. Therefore, there exist many tools that will do the job for us. One such tool is npm minifier. Visit https://www.npmjs.com/package/minifier for more.

Let’s go ahead and install it:

sudo npm install -g minifier

Once installed, we can minify our style sheet by typing the following command:

minify path-to-myphoto.css

Here, path-to-myphoto.css represents the path to our MyPhoto style sheet. Go ahead and execute the command. Once minification is complete, you should see the Minification complete message. A new CSS file (myphoto.min.css) will have been created inside the directory containing the myphoto.css file. The new file should be 2,465 bytes. Our original myphoto.css file is 3,073 bytes. Minifying our style sheet just reduced the number of bytes to send by roughly 19%!

Go ahead and update the head of our HTML document to reference the new, minified stylesheet (note that, for the sake of keeping this example short and simple, we will skip the minimization of our other style sheets: a11yhcm.css, alert.css, carousel.css, and myphoto-hcm.css):

<link rel=”stylesheet” href=”styles/myphoto.min.css” />

It is worth noting that, apart from CSS minification, minifier also allows you to minify JavaScript files. For example, to minify our alert.js file, simply type this:

minify path-to-alert.js

Once again, as soon as the minification is complete, you should see the Minification complete message. Similar to earlier, a new file (alert.min.js) will have been created inside the directory containing the alert.js file.

Source: Jakobus Benjamin, Marah Jason (2018), Mastering Bootstrap 4: Master the latest version of Bootstrap 4 to build highly customized responsive web apps, Packt Publishing; 2nd Revised edition.

Leave a Reply

Your email address will not be published. Required fields are marked *