Skip to content

Instantly share code, notes, and snippets.

@progers
Created August 21, 2016 05:04
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 progers/ea2e236105e894a3b592fa264c43fbf4 to your computer and use it in GitHub Desktop.
Save progers/ea2e236105e894a3b592fa264c43fbf4 to your computer and use it in GitHub Desktop.
Minimize styles
<!DOCTYPE HTML>
<div id='diva' style="width: 300px; height: 200px; border: 0px solid rgb(0, 0, 0); background: green;">hello world</div>
<script>
function minimizeStyleAttribute(element) {
var originalStyleAttr = element.getAttribute('style');
var originalComputedStyle = getComputedStyle(element, null);
// Save off the original CSSComputedStyle values in a map because the object is 'live' and
// modifying the style attribute will change it.
var originalComputedStyleMap = {};
for (var propertyIndex = 0; propertyIndex < originalComputedStyle.length; propertyIndex++) {
var propertyName = originalComputedStyle.item(propertyIndex);
originalComputedStyleMap[propertyName] = originalComputedStyle.getPropertyValue(propertyName);
}
// We need to iteratively compute the required styles because removing some properties can
// change other properties. For example, removing 'border-style' can change 'border-width'.
var requiredStyleMap = {};
var maxRequiredStylesIterations = 5;
do {
// Compute the current style attribute for |requiredStyleMap|.
var currentStyleAttr = '';
for (var propertyName in requiredStyleMap)
currentStyleAttr += propertyName + ':' + requiredStyleMap[propertyName] + '; ';
// Apply the style attribute and compare the computed css properties to the original
// properties, adding any differences to |requiredStyleMap|.
element.setAttribute('style', currentStyleAttr);
var currentComputedStyle = getComputedStyle(element, null);
var foundNewRequiredStyle = false;
for (var propertyName in originalComputedStyleMap) {
var originalComputedValue = originalComputedStyleMap[propertyName];
if (originalComputedValue !== currentComputedStyle.getPropertyValue(propertyName)) {
requiredStyleMap[propertyName] = originalComputedValue;
foundNewRequiredStyle = true;
}
}
// If no new styles were found we can stop looking.
if (!foundNewRequiredStyle)
break;
} while (--maxRequiredStylesIterations !== 0);
var finalStyleAttr = '';
for (var propertyName in requiredStyleMap)
finalStyleAttr += propertyName + ':' + requiredStyleMap[propertyName] + '; ';
return finalStyleAttr;
}
diva.setAttribute('style', minimizeStyleAttribute(diva));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment