Document. styleSheets stores a set of all CSS rules on the current page. You can traverse all the selectors defined in the <style> page and access the selectorText attribute to obtain the matching rules of the selector. Then, pass the rule to document. querySelectorAll to obtain the list of elements matching the rule on the page.
Here we only need to calculate the coverage of CSS rules, so we can access querySelectorAll (). length. By sorting, we can see the usage of each CSS.
The code is simple.
Copy codeThe Code is as follows:
Var usage = [];
Var sheets = document. styleSheets;
For (var I = sheets. length-1; I! =-1; I --){
Var rules = sheets [I]. rules;
For (var j = rules. length-1; j! =-1; j --){
Var rule = rules [j];
Var text = rule. selectorText;
Usage. push ({name: text, count: document. querySelectorAll (text). length });
}
}
Usage. sort (function (a, B) {return a. count-B. count });
For (var I = usage. length-1; I! =-1; I --){
Console. log ("selector:" + usage [I]. name + "\ n \ t matching count:" + usage [I]. count );
}
Call F12 and paste the code to the console and press Enter.
Of course, due to permission issues, CSS imported externally cannot be accessed in any way. If the broken IE of styleSheets is not supported, you can use expression or behaviour. htc to try it another day.
This is where the pure JS implementation is. Later, we will use a local program to implement external CSS analysis.
By the way, paste a test result:
What CSS is useless at a Glance:
Of course, 0 matching does not mean it is useless. The most typical example is: hover, which can be matched only when the mouse moves up. You can also use className to control [attr =], # dynamic ID, dynamic element .... And so on.
So the above Code is of little significance, and currently mainstream browsers have built-in Profiles function, and can track the number of elements matching the selector in real time, so it makes some sense to be an IE version :)