Giảm khoảng 5% kích thước CSS làm cho tốc độ load CS Strong trang web giảm đáng kể
public static string RemoveWhiteSpaceFromStylesheets(string body)
{
body = Regex.Replace(body, @"[a-zA-Z]+#", "#"); // ul#
body = Regex.Replace(body, @"[\n\r]+\s*", string.Empty); // space
body = Regex.Replace(body, @"\s+", " ");
body = Regex.Replace(body, @"\s?([:,;{}])\s?", "$1");
body = body.Replace(";}", "}");
body = Regex.Replace(body, @"([\s:]0)(px|pt|%|em)", "$1");
// Remove comments from CSS
body = Regex.Replace(body, @"/\*[\d\D]*?\*/", string.Empty);
return body;
}
static void Main(string[] args)
{
string minstyle = RemoveWhiteSpaceFromStylesheets(File.ReadAllText(@"..\..\style.css"));
File.WriteAllText(@"..\..\style-min.css", minstyle);
Console.WriteLine("Done!");
Console.Read();
}
VB.NET
Imports System.IO
Imports System.Text.RegularExpressions
Module MinCSS
Sub Main()
Dim minstyle As String = RemoveWhiteSpaceFromStylesheets(File.ReadAllText("..\..\style.css"))
File.WriteAllText("..\..\style-min.css", minstyle)
Console.Write("Done!")
Console.Read()
End Sub
Public Function RemoveWhiteSpaceFromStylesheets(ByVal body As String) As String
body = Regex.Replace(body, "[a-zA-Z]+#", "#")
body = Regex.Replace(body, "[\n\r]+\s*", String.Empty)
body = Regex.Replace(body, "\s+", " ")
body = Regex.Replace(body, "\s?([:,;{}])\s?", "$1")
body = body.Replace(";}", "}")
body = Regex.Replace(body, "([\s:]0)(px|pt|%|em)", "$1")
' Remove comments from CSS
body = Regex.Replace(body, "/\*[\d\D]*?\*/", String.Empty)
Return body
End Function
End Module
Press F5 chúng ta sẻ có 1 file style-min.css với kích thước nhỏ hơn so với file gốc.
http://code2code.googlecode.com/svn/trunk/MinimizeCSS
Reference
MinimizeCSS.rar (75.41 kb)