Count number of selectors in a css file

你说的曾经没有我的故事 提交于 2019-11-28 15:48:51
jetli13

The following snippet can be run in the Firebug console in Firefox to count the total number of CSS selectors (not just CSS rules) and check whether it reaches the limit of 4095 selectors per stylesheet:

var
  styleSheets = document.styleSheets,
  totalStyleSheets = styleSheets.length;

for (var j = 0; j < totalStyleSheets; j++){
  var
    styleSheet = styleSheets[j],
    rules = styleSheet.cssRules,
    totalRulesInStylesheet = rules.length,
    totalSelectorsInStylesheet = 0;

  for (var i = 0; i < totalRulesInStylesheet; i++) {
    if (rules[i].selectorText){
      totalSelectorsInStylesheet += rules[i].selectorText.split(',').length;
    }
  }
  console.log("Stylesheet: "+styleSheet.href);
  console.log("Total rules: "+totalRulesInStylesheet);
  console.log("Total selectors: "+totalSelectorsInStylesheet);
}

My project, Bless CSS, could be what you're looking for. It will analyze files and split them at the optimum point based on the selector limit.

It's also built in to CodeKit.

There is this bookmarklet that tells you the number of used CSS rules out of the total CSS rules (which you are interested in).

CSS Crunch

This will do inline CSS...

var selectors = 0;

$('style').each(function() {

   var styles = $(this).html();

   // Strip comments
   styles = styles.replace(/\/\*.+?\*\//sg, ''); 

   var matches = styles.match(/\{[\s.]*\}/g);

   selectors += matches.length;

});

jsFiddle.

Search & replace "{" by "{" in your CSS file. Most editors wil tell how many replacements you’ve done…

Simple algorithm for counting the selectors if you want to do it as part of the build process or simply don't want to do it in JS:

Replace the texts between "{" and "}" with a "," and then calculate the number of ",". This will give you the number of selectors on the file.

a bit to late, but for anyone how's looking for a css selector counter: http://snippet.bevey.com/css/selectorCount.php it's very simple, and can work with more than one stylesheet, it even tells you when you hit the 4096 limit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!