Skip to content

Instantly share code, notes, and snippets.

@fastmover
Forked from psebborn/countCSSRules.js
Last active October 12, 2015 00:08
Show Gist options
  • Save fastmover/3940667 to your computer and use it in GitHub Desktop.
Save fastmover/3940667 to your computer and use it in GitHub Desktop.
Count the number of rules and selectors for CSS files on the page. Flags up the >4096 threshold that confuses IE
function countCSSRules() {
var results = '',
log = '',
totalCount = 0,
totalRules = 0,
fileCount = 0;
if (!document.styleSheets) {
return;
}
for (var i = 0; i < document.styleSheets.length; i++) {
countSheet(document.styleSheets[i]);
fileCount += 1;
}
function countSheet(sheet) {
var count = 0;
if (sheet && sheet.cssRules) {
for (var j = 0, l = sheet.cssRules.length; j < l; j++) {
if(sheet.cssRules[j].selectorText != undefined) {
count += sheet.cssRules[j].selectorText.split(',').length;
} else if( sheet.cssRules[j].href != undefined) {
//A stylesheet was imported in this stylesheet, so load that.
countSheet(sheet.cssRules[j].styleSheet);
}
}
log += '\nFile: ' + (sheet.href ? sheet.href : 'inline <style> tag');
log += '\nRules: ' + sheet.cssRules.length;
log += '\nSelectors: ' + count;
log += '\n--------------------------';
if (count >= 4096) {
results += '\n********************************\nWARNING:\n There are ' + count + ' CSS rules in the stylesheet ' + sheet.href + ' - IE will ignore the last ' + (count - 4096) + ' rules!\n';
}
totalCount += count;
totalRules += sheet.cssRules.length;
}
}
console.log(log);
console.log(results);
console.log('Total Rules: ' + totalRules)
console.log('Total Selectors: ' + totalCount)
console.log('Total Files: ' + fileCount)
};
countCSSRules();
@christianhaller
Copy link

nice work. thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment