Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating new css from old css file that consists only needed selectors using Javascript

I have css file that has over 2000 lines. Is there any way to create mini js function that will parse html, fetch only needed selectors from this .css file and generate new css?

like image 783
heron Avatar asked Nov 26 '25 15:11

heron


1 Answers

Use IE9 (for its more robust StyleSheet DOM). Run this script in your JavaScript console:

var used = [], unused = [];
[].forEach.call(document.styleSheets, function (ss) {
    [].forEach.call(ss.cssRules, function (r) {
        if (document.querySelector(r.selectorText)) {
            used.push(r);
        } else {
            unused.push(r);
        }
    });
});
console.log("Selectors that exist in this page: " + used.length);
console.log("Selectors that do not exist in this page: " + unused.length);

used.map(function (rule) {
    return rule.cssText;
}).join("\n");

It will print out in the console only the rules that you need for a given page.

like image 135
gilly3 Avatar answered Nov 29 '25 05:11

gilly3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!