Created
February 25, 2021 21:44
-
-
Save DV8FromTheWorld/933d55f9fbe5dc6945d0e78b28285ef8 to your computer and use it in GitHub Desktop.
get-css-rules.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Iterates through all stylesheets loaded onto the page and returns an array of all css rules. | |
* Useful for getter a quick glance at roughly how many css selector rules there are on a page. | |
*/ | |
function getCssRules() { | |
const skipped = {} | |
const rules = Array.from(document.styleSheets) | |
.flatMap(sheet => Array.from(sheet.rules) | |
.flatMap(rule => { | |
const ruleType = rule.constructor.name | |
if (ruleType === 'CSSMediaRule') { //Media rule | |
return Array.from(rule.cssRules).map(mediaRule => `@media(${rule.conditionText}) ${mediaRule.selectorText}`) | |
} | |
if (!rule.selectorText) { | |
skipped[ruleType] = (skipped[ruleType] || 0) + 1 | |
return false | |
} | |
return rule.selectorText || rule | |
}) | |
) | |
.filter(rule => !!rule) | |
if (Object.keys(skipped)) { | |
/* eslint-disable-next-line no-console */ | |
console.log("Skipped rules", skipped) | |
} | |
return rules | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment