20 lines of code to write a CSS coverage test script

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.

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. 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 :)

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.