Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Run this in the dev tools console to ensure none of your stylesheets have too many rules / selectors for legacy IE (IE9 and below).
function countCSSRules() {
var results = '',
log = '',
slen = document.styleSheets.length;
if (!document.styleSheets) {
return;
}
for (var i = 0; i < slen; i++) {
countSheet(document.styleSheets[i]);
}
function countSheet(sheet) {
var count = 0;
// Added a workaround for Firefox Security Error when accessing cross-domain
// stylesheets. See http://stackoverflow.com/a/23613052/13019
// cssRules respects same-origin policy, as per
// https://code.google.com/p/chromium/issues/detail?id=49001#c10.
try {
// In Chrome, if stylesheet originates from a different domain,
// sheet.cssRules simply won't exist. I believe the same is true for IE, but
// I haven't tested it.
//
// In Firefox, if stylesheet originates from a different domain, trying
// to access sheet.cssRules will throw a SecurityError. Hence, we must use
// try/catch to detect this condition in Firefox.
if (sheet && sheet.cssRules) {
for (var j = 0, l = sheet.cssRules.length; j < l; j++) {
if (!sheet.cssRules[j].selectorText) {
if (sheet.cssRules[j].cssRules) {
for (var m = 0, n = sheet.cssRules[j].cssRules.length; m < n; m++) {
if(sheet.cssRules[j].cssRules[m].selectorText) {
count += sheet.cssRules[j].cssRules[m].selectorText.split(',').length;
}
}
}
}
else {
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';
}
}
} catch(e) {
// Rethrow exception if it's not a SecurityError. Note that SecurityError
// exception is specific to Firefox.
if(e.name !== 'SecurityError') {
throw e;
return;
}
}
return results;
}
console.log(log);
console.log(results);
};
countCSSRules();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.