简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM