Minifying CSS and JavaScript

Once you have improved the MyPhoto style rules so 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 message Minification complete. A new CSS file (myphoto.min.css) will have been created inside the directory containing the myphoto.css file. The new file should be 3,358 bytes. Our original myphoto.css file is 3,945 bytes. Minifying our style sheet just reduced the number of bytes to send by roughly 15%!

Go ahead and update the head of our HTML document to reference the new, minified style sheet:

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

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

    minify path-to-alert.js

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.231.128