简体   繁体   English

从旧的css文件生成新的css,该文件仅包含使用Javascript的所需选择器

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

I have css file that has over 2000 lines. 我有超过2000行的css文件。 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? 有没有办法创建将解析html的mini js函数,只从这个.css文件中获取所需的选择器并生成新的css?

Use IE9 (for its more robust StyleSheet DOM). 使用IE9(更强大的StyleSheet DOM)。 Run this script in your JavaScript console: 在JavaScript控制台中运行此脚本:

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 ? 不是一个js解决方案,但你检查了尘土我

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 :( 但是,它不适用于Firefox 8 :(

Here is a javascript solution. 是一个javascript解决方案。 I havent tried this one but Dust Me has done the trick for me in the past. 我没试过这个,但是Dust Me过去曾为我做过这个伎俩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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