Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function countCSSRules() {
var results = '',
log = '';
if (!document.styleSheets) {
return;
}
for (var i = 0; i < document.styleSheets.length; i++) {
countSheet(document.styleSheets[i]);
}
function countSheet(sheet) {
var count = 0;
if (sheet && sheet.cssRules) {
for (var j = 0, l = sheet.cssRules.length; j < l; j++) {
//Check for imports
if (sheet.cssRules[j] instanceof CSSImportRule)
{
countSheet(sheet.cssRules[j].styleSheet);
}
if( !sheet.cssRules[j].selectorText ) {
continue;
}
count += sheet.cssRules[j].selectorText.split(',').length;
}
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';
}
}
}
console.log(log);
console.log(results);
};
countCSSRules();
@darioalbanesi

This comment has been minimized.

Copy link

@darioalbanesi darioalbanesi commented Mar 13, 2015

nice! thank you!

@phawxby

This comment has been minimized.

Copy link

@phawxby phawxby commented Feb 11, 2016

Yeah, this works brilliantly! Thanks!

@ElijahLynn

This comment has been minimized.

Copy link

@ElijahLynn ElijahLynn commented Oct 6, 2017

Works great, thanks! I made some suggested changes based on IE9 vs IE10+ selector limits, these are the changes:

if (count >= 65534) {
    results += '\n********************************\nWARNING:\n There are ' + count + ' CSS rules in the stylesheet ' + sheet.href + ' - IE10 and newer will ignore the last ' + (count - 4096) + ' rules!\n';
}
if (count >= 4096) {
    results += '\n********************************\nWARNING:\n There are ' + count + ' CSS rules in the stylesheet ' + sheet.href + ' - IE9 and older will ignore the last ' + (count - 4096) + ' rules!\n';
    results += '\n********************************\n@see https://blogs.msdn.microsoft.com/ieinternals/2011/05/14/stylesheet-limits-in-internet-explorer/';
}

https://gist.github.com/ElijahLynn/07ab9a7525b1511615db558473e52611

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