Use native Js for CSS formatting and Compression

Source: Internet
Author: User
Preface

I have always liked to collect special webpage effects. In many cases, CSS is compressed, which is inconvenient to view. Sometimes, to reduce the file size, it will also compress its own CSS. There are a lot of such services available on the Internet, but they are not satisfactory. Therefore, we plan to write a JS to format and compress CSS.

Principle

The structure of CSS is as follows:

Selector {
CSS attribute Declaration: value;
}

Therefore, CSS formatting is relatively simple, which can be roughly divided into the following steps;

1. Merge multiple spaces into one and remove line breaks.

2. Group processed strings "{"

3. traverse the group and group the parts containing "}" again "}"

4. process the grouped data by adding spaces and line breaks.

It's easy to compress CSS. Combine spaces and remove line breaks.

Format

The preceding steps are implemented step by step.

Initialization:

function formathtmljscss(source, spaceWidth, formatType) {
this.source = source;
this.spaceStr = " ";
if (!isNaN(spaceWidth)) {
if (spaceWidth > 1) {
this.spaceStr = "";
for (var i = 0; i < spaceWidth; i++) {
this.spaceStr += " ";
}
}
else {
this.spaceStr = "\t";
}
}
this.formatType = formatType;
this.output = [];
}

The parameters here are the CSS code to be formatted, the space width before the CSS attribute declaration, type (format/compression)

1. Combine multiple spaces into one and remove the line feed:

formathtmljscss.prototype.removeSpace = function () {
this.source = this.source.replace(/\s+|\n/g, " ")
.replace(/\s*{\s*/g, "{")
.replace(/\s*}\s*/g, "}")
.replace(/\s*:\s*/g, ":")
.replace(/\s*;\s*/g, ";");
}

2. Group processed strings "{"

formathtmljscss.prototype.split = function () {
var bigqleft = this.source.split("{");
}

3. traverse the group and group the parts containing "}" again "}"

formathtmljscss.prototype.split = function () {
var bigqleft = this.source.split("{");
var bigqright;
for (var i = 0; i < bigqleft.length; i++) {
if (bigqleft[i].indexOf("}") != -1) {
bigqright = bigqleft[i].split("}");
}
else {

}
}
}

4. process the grouped data by adding spaces and line breaks.

The processing here is mainly divided into taking out the CSS attribute declaration and value, and then adding spaces and line breaks:

formathtmljscss.prototype.split = function () {
var bigqleft = this.source.split("{");
var bigqright;
for (var i = 0; i < bigqleft.length; i++) {
if (bigqleft[i].indexOf("}") != -1) {
bigqright = bigqleft[i].split("}");
var pv = bigqright[0].split(";");
for (var j = 0; j < pv.length; j++) {
pv[j] = this.formatStatement(this.trim(pv[j]),true);
if (pv[j].length > 0) {
this.output.push(this.spaceStr + pv[j] + ";\n");
}
}
this.output.push("}\n");
bigqright[1] = this.trim(this.formatSelect(bigqright[1]));
if (bigqright[1].length > 0) {
this.output.push(bigqright[1], " {\n");
}
}
else {
this.output.push(this.trim(this.formatSelect(bigqleft[i])), " {\n");
}
}
}

Several methods are called: trim, formatselect, and formatstatement.

Trim:From the name, we can see that the first and last spaces are removed;

formathtmljscss.prototype.trim = function (str) {
return str.replace(/(^\s*)|(\s*$)/g, "");
}

Formatselect:Is to process the selector part of the syntax, the practice is to add a space before ".", remove the spaces before and after ", and combine multiple spaces into one:

formathtmljscss.prototype.formatSelect = function (str) {
return str.replace(/\./g, " .")
.replace(/\s+/g, " ")
.replace(/\. /g, ".")
.replace(/\s*,\s*/g, ",");
}

Formatstatement:It is the syntax used to process the "CSS attribute Declaration: value;" part. The method is to add a space after ":", Merge multiple spaces into one, and remove the spaces after, remove the space before "PX", remove the space on both sides, and remove the space before:

formathtmljscss.prototype.formatStatement = function (str, autoCorrect) {
str = str.replace(/:/g, " : ")
.replace(/\s+/g, " ")
.replace("# ", "#")
.replace(/\s*px/ig, "px")
.replace(/\s*-\s*/g, "-")
.replace(/\s*:/g, ":");

return str;
}
Call

The call part is relatively simple. for formatting, spaces and line breaks are removed and grouped for processing. For compression, spaces and line breaks are removed:

formathtmljscss.prototype.formatcss = function () {
if (this.formatType == "compress") {
this.removeSpace();
}
else {
this.removeSpace();
this.split();
this.source = this.output.join("");
}
}

Interface HTML code:

View code

<Div id = "content">
<Div class = "Container">
<Div class = "box">
<Div class = "Main">
<H2> CSS formatting/compression </H2>
<Div id = "blurb">
<Fieldset id = "options">
<Button id = "Submit">
<Span> Format/compress & nbsp; </span>
</Button> <br/>
<Span> indent: </span>
<Ul>
<Li>
<Select name = "tabsize" id = "tabsize">
<Option value = "1"> tab indent </option>
<Option value = "2"> 2 space indentation </option>
<Option selected = "selected" value = "4"> 4 Space indentation </option>
</SELECT>
</LI>
</Ul> <br/>
<Span> type: </span> <br/>
<Input type = "radio" name = "format_type" value = "format" Checked = "checked" id = "format_format"/> <label for = "format_format"> Format </ label>
<Input type = "radio" name = "format_type" value = "compress" id = "format_compress"/> <label for = "format_compress"> compression </label>
</Fieldset>
</Div>
<Div id = "beauty">
<Fieldset id = "textarea-wrap">
<Textarea rows = "20" Cols = "40" id = "Source"> </textarea>
</Fieldset>
</Div>
</Div>
</Div>
</Div>
</Div>

Bind an event to the page element button:

View code

window.onload = function () {
var submitBtn = document.getElementById("submit");
var tabsize = document.getElementById("tabsize");
var sourceCon = document.getElementById("source");
var size = 4;
var formatType = "format";
submitBtn.onclick = function () {
var radios = document.getElementsByName("format_type");
for (i = 0; i < radios.length; i++) {
if (radios[i].checked) {
formatType = radios[i].value;
break;
}
}
var format = new formathtmljscss(sourceCon.value, size, formatType);
format.formatcss();
sourceCon.value = format.source;
}
tabsize.onchange = function () {
size = this.options[this.options.selectedIndex].value;
submitBtn.click();
return false;
}
}
Demo

Welcome to the test!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.