Skip to content

Instantly share code, notes, and snippets.

@CYBAI
Forked from emilio/reduce-css.js
Created March 22, 2019 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CYBAI/4ff678a2cde2fdb6350a3e76a86b6a5d to your computer and use it in GitHub Desktop.
Save CYBAI/4ff678a2cde2fdb6350a3e76a86b6a5d to your computer and use it in GitHub Desktop.
Ever wanted to reduce all the CSS in a test-case to the minimmum? :)
var USELESS_PROPERTIES = [];
function processContainer(container) {
if (container instanceof CSSSupportsRule)
if (!CSS.supports(container.conditionText))
return false;
if (container instanceof CSSMediaRule)
if (!matchMedia(container.conditionText).matches)
return false;
if (container.media && container.media.mediaText)
if (!matchMedia(container.media.mediaText).matches)
return false;
for (let rules = container.cssRules, i = 0; i < rules.length; ++i) {
let rule = rules[i];
if (!processRule(rule)) {
container.deleteRule(i);
i--;
}
}
return !!container.cssRules.length;
}
function processRule(rule) {
if (rule instanceof CSSGroupingRule)
return processContainer(rule);
if (!(rule instanceof CSSStyleRule))
return false;
let selector = rule.selectorText.replace(/::before/g, "").replace(/::after/g, "");
if (selector.includes("form") || selector.includes("dropdown"))
return true;
if (!document.querySelector(selector))
return false;
let style = rule.style;
for (let i = 0; i < style.length; ++i) {
let property = style[i];
for (const prop of USELESS_PROPERTIES) {
if (property.indexOf(prop) != -1) {
style.removeProperty(property);
i--;
}
}
}
return !!style.length;
}
for (let sheet of document.styleSheets)
if (!processContainer(sheet))
if (sheet.ownerNode)
sheet.ownerNode.remove();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment