Last Updated: February 25, 2016
·
10.25K
· tylerlee

Count how many css selectors are on a page

Just used this nifty script from: https://gist.github.com/1885511
to count how many CSS selectors were included on a page. Had a harder time googling for it than I should have so hopefully you won't have that issue.

I just dropped this into chrome's console on the page I wanted to check out.

 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++) {
                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();

3 Responses
Add your response

Thanks!!! You helped me stop wasting even more time by finding the problem why IE9 did not use all my styles.

over 1 year ago ·

This is a nice trick, however be aware that due to Cross Domain permissions, the sheets outside your domain will say they have 0 rules...

over 1 year ago ·

Perfecto !!

over 1 year ago ·