forked from juanxo/css-rule-checker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrulechecker.js
85 lines (75 loc) · 3.01 KB
/
rulechecker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
(function(){
// Load jQuery if it hasn't be previously loaded
if (!window.jQuery) {
script = document.createElement( 'script' );
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
script.onload=checkRules;
document.body.appendChild(script);
jQuery.noConflict();
}
else {
checkRules();
}
function checkRules() {
var stylesheets = document.styleSheets;
var totalRuleCount = 0;
var totalAppliedRuleCount = 0;
for ( var index = 0; stylesheets && index < stylesheets.length; ++index ){
var currentStylesheet = stylesheets[index];
if ( currentStylesheet != null){
var stylesheetName = "Inline Style";
if (currentStylesheet.ownerNode.tagName.toLowerCase() === "link") {
stylesheetName = currentStylesheet.href;
}
console.info("Stylesheet " + index + ": " + stylesheetName);
var rules = currentStylesheet.rules;
for ( var j = 0; rules && j < rules.length; ++j ){
var currentRule = rules[j];
if ( currentRule instanceof CSSImportRule ) {
var result = checkImportRule(currentRule);
totalAppliedRuleCount += result[0];
totalRuleCount += result[1];
} else {
totalRuleCount += 1;
var selectorText = currentRule.selectorText;
var matchedElements = jQuery(selectorText);
if ( matchedElements.length > 0 ){
totalAppliedRuleCount += 1;
console.info(selectorText + " applies to " + matchedElements.length + " elements");
} else {
console.warn(selectorText + " doesn't apply");
}
}
}
}
}
console.info("There are " + totalRuleCount + " rules");
var notAppliedRuleCount = totalRuleCount - totalAppliedRuleCount;
console.info("Applied: " + totalAppliedRuleCount + ", Not applied: " + notAppliedRuleCount);
}
// Iterates over import rule, returning [appliedRuleCount, totalRuleCount] for that import.
function checkImportRule( importRule ) {
var stylesheet = importRule.styleSheet;
var appliedRulesCount = 0;
var totalRulesCount = 0;
for ( var i = 0; stylesheet.rules && i < stylesheet.rules.length; ++i ) {
var currentRule = stylesheet.rules[i];
if ( currentRule instanceof CSSImportRule ) {
var results = checkImportRule(currentRule);
appliedRulesCount += results[0];
totalRulesCount += results[1];
} else {
totalRulesCount += 1;
var selectorText = currentRule.selectorText;
var matchedElements = jQuery(selectorText);
if ( matchedElements.length > 0 ){
appliedRulesCount += 1;
console.info(selectorText + " applies to " + matchedElements.length + " elements");
} else {
console.warn(selectorText + " doesn't apply");
}
}
}
return [appliedRulesCount, totalRulesCount];
}
})();