Write the CSS coverage test script with only 20 lines of code.

Source: Internet
Author: User

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.

By the way, paste a test result:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.