heron
heron

Reputation: 3661

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?

Upvotes: 3

Views: 224

Answers (2)

Zac
Zac

Reputation: 12836

Not a js solution but have you checked out Dust Me?

From the site :

It extracts all the selectors from all the stylesheets on the page you're viewing, then analyzes that page to see which of those selectors are not used. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they're encountered.

You can test pages individually, or spider an entire site, and you'll end up with a profile of which selectors are not used anywhere.

However, it is not available for Firefox 8 :(

Here is a javascript solution. I havent tried this one but Dust Me has done the trick for me in the past.

Upvotes: 0

gilly3
gilly3

Reputation: 91497

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.

Upvotes: 2

Related Questions