With uncss, put your style sheets on a diet

Uncs is a tool under Node.js that allows you to analyze style sheets in relation to the use you make of them on your site and remove all unnecessary rules in order to drastically reduce its weight and therefore speed up its loading!
Let's see how it works, if it's really effective and how to use it.

How does it work?

Developed by Giacomo Martino since April 2013, its operation is quite simple. When launched, the tool starts a Phantomjs to scan the targeted HTML page, retrieves all existing CSS rules, checks for each one if there is a corresponding DOM node in the page, and if not, it removes this unnecessary rule.

By reading this explanation, you are probably already thinking that it does not work with dynamically added styles or html nodes, and you are partly right. If the style or the node is not in the page when it starts (in html or added to the onload in JavaScript) uncss will consider it useless and delete it. Fortunately, there are several ways to tell it about exceptions. We will come back to this in the third part of this article.

Is it really effective?

Take the example of the website JS Republic, it embeds in CSS framework normalize, Skeleton et Animate.css. Concatenated and minified with site-specific code, the resulting stylesheet weighs 104 KB without uncss. With uncss the sheet becomes lighter and goes to 27 KB!
Either a weight gain of more than 60 %

How to use it?

There are integrations with Gulp and Grunt, but in this article I'm focusing on a Gulp example.
Here is a simple example of use in a file gulpfile.js (of course, don't forget to install it via npm install gulp-uncss –save-dev before trying to use it)

const uncss = require('gulp-uncss');
gulp.task('css', () =>
    gulp.src('public/css/**/*.css')
        .pipe(uncss({
            html: ['public/index.html'],
            ignore: [/^#konami-overlay/]
        }))
        .pipe(gulp.dest('build/public/css'));
);

You will have noted the property html which allows uncss to specify the html file(s) (or url) to scan as well as the property ignore which allows to define css selectors to be ignored during filtering.
These selectors can be given in text format or, more interestingly, in the form of a regular expression. This has the advantage of being able to match a group of rules in one line. In our example, we exclude all css rules with a selector starting with “#konami-overlay”.
To learn more about the tool and its use, I invite you to consult the uncss documentation.
Matthew Breton CTO at JS Republic
[separator type=”” size=”” icon=”star”] [actionbox color=”default” title=”” description=”JS-REPUBLIC is a service company specializing in JavaScript development. We are an approved training center. Find all our technical training on our partner site dedicated to Training” btn_label=”Our training” btn_link=”http://training.ux-republic.com” btn_color=”primary” btn_size=”big” btn_icon=”star” btn_external =”1″]