Skip to content

Instantly share code, notes, and snippets.

@KeySeeDev
Last active April 18, 2018 20:30
Show Gist options
  • Save KeySeeDev/2e8ba95d5e7bcdd50b7ea8f084f20474 to your computer and use it in GitHub Desktop.
Save KeySeeDev/2e8ba95d5e7bcdd50b7ea8f084f20474 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Compress css with javascript</title>
<style>
* {box-sizing: border-box;margin: 0;padding: 0}
html,body {font-size: 0;height: 100%}
:focus {outline: none}
textarea {border: none;display: inline-block;height: 100%;padding: 10px;white-space: nowrap;width: 50%}
#compress {background: #FFF;border-radius: 50%;font-size: 10px;left: 50%;margin: -35px 0 0 -35px;padding: 27.5px 0;position: absolute;top: 50%;width: 70px}
#input {background: #ffd5d5}
#output {background: #d9fddd}
</style>
</head>
<body>
<textarea id="input"></textarea>
<input type="submit" id="compress" value="COMPRESS">
<textarea id="output"></textarea>
<script>
var input = document.getElementById('input');
var output = document.getElementById('output');
var compress = document.getElementById('compress');
compress.onclick = function() {
var compressed = input.value;
//remove comments
compressed = compressed.replace(/\/\*[\s\S]+?\*\//g, "");
//replace whitespaces and newlines
compressed = compressed.replace(/\s{2,}/g, '');
compressed = compressed.replace(/\n/g, '');
//new line for each rule
compressed = compressed.replace(/\}/g, '}\n');
//sort css rules alphabetally
compressed = compressed.replace(/{(.+)}/g, sort_css_rules);
output.value = compressed;
}
function sort_css_rules(match, contents, s, offset) {
var new_contents = contents.split(';');
new_contents = new_contents.sort(function(a,b) {
var textA = a.toUpperCase();
var textB = b.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});
new_contents = new_contents.join(';');
new_contents = '{'+new_contents+'}';
new_contents = new_contents.replace('{;','{');
return new_contents;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment