Created
August 17, 2024 23:08
-
-
Save souporserious/829f7f6efa536eaed993e6c162f8da25 to your computer and use it in GitHub Desktop.
This file contains 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
const seenStyleElements = new Set<HTMLStyleElement>() | |
const cache = new Set<string>() | |
function processStyleRule( | |
rule: CSSStyleRule, | |
sheet: CSSStyleSheet, | |
index: number | |
) { | |
const selector = rule.selectorText | |
const className = selector.match(/\.([a-zA-Z0-9_-]+)/)![1]! | |
if (cache.has(className)) { | |
sheet.deleteRule(index) | |
} else { | |
cache.add(selector) | |
} | |
} | |
function processMediaRule(mediaRule: CSSMediaRule, sheet: CSSStyleSheet) { | |
const rules = mediaRule.cssRules | |
for (let index = rules.length - 1; index >= 0; index--) { | |
const rule = rules[index]! | |
if (rule instanceof CSSStyleRule) { | |
processStyleRule(rule, sheet, index) | |
} | |
} | |
} | |
function processStyleElement(node: HTMLStyleElement) { | |
const sheet = node.sheet as CSSStyleSheet | |
const rules = sheet.cssRules | |
if (rules) { | |
for (let index = rules.length - 1; index >= 0; index--) { | |
const rule = rules[index]! | |
if (rule instanceof CSSStyleRule) { | |
processStyleRule(rule, sheet, index) | |
} else if (rule instanceof CSSMediaRule) { | |
processMediaRule(rule, sheet) | |
} | |
} | |
} | |
seenStyleElements.add(node) | |
} | |
const observer = new MutationObserver((mutations) => { | |
for ( | |
let mutationIndex = 0; | |
mutationIndex < mutations.length; | |
mutationIndex++ | |
) { | |
const mutation = mutations[mutationIndex]! | |
const addedNodes = mutation.addedNodes | |
for (let nodeIndex = 0; nodeIndex < addedNodes.length; nodeIndex++) { | |
const node = addedNodes[nodeIndex]! as HTMLStyleElement | |
if ( | |
node.tagName === 'STYLE' && | |
node.dataset.precedence?.startsWith('rs') && | |
!seenStyleElements.has(node) | |
) { | |
processStyleElement(node) | |
} | |
} | |
} | |
}) | |
document | |
.querySelectorAll<HTMLStyleElement>('style[data-precedence^="rs"]') | |
.forEach((node) => { | |
processStyleElement(node) | |
}) | |
observer.observe(document.head, { childList: true }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment