只需20行代碼就可以寫出CSS覆蓋率測試指令碼

來源:互聯網
上載者:User

  document.styleSheets裡儲存了當前頁面上所有CSS規則的集合。通過它可以遍曆出頁面<style>裡定義的所有selector,訪問selectorText屬性可得選取器的匹配規則。然後將規則規則傳遞給 document.querySelectorAll 即可擷取頁面內匹配此規則的元素列表。

  這裡我們只求CSS規則的覆蓋率,所以訪問 querySelectorAll().length 即可。通過排序就可看出各個CSS使用方式。

  代碼很簡單。

複製代碼 代碼如下: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("選取器:" + usage[i].name + "\n\t匹配數:" + usage[i].count);
}

  呼出F12,把代碼粘到console裡斷行符號即可。

  當然由於許可權問題,外部匯入的CSS無論如何都訪問不到,暫時先不考慮了。至於不支援styleSheets的破IE嘛,可以考慮用expression或者behaviour.htc,改天試試看。

  順便貼個測試結果:

相關文章

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.