Quantcast Giảm kích thước CSS StyleSheet Using .Net

Giảm kích thước CSS StyleSheet Using .Net

by Neon Quach 3. Tháng Ba 2010 02:15

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)

Tags: , ,


Categories: css | c# | vb.net

blog comments powered by Disqus

About me

I'm  currently employed as Software developer at sutrixmedia.com and also a Microsoft Certified Technology Specialist (MCTS), Microsoft Certified Professional Developer (MCPD) in Net Framework 2.0 and 3.5: Web Applications and MCTS .NET Framework 3.5, ADO.NET Applications

Nhà Tài Trợ

 Honda Air Blade 125cc

Powered by BlogEngine.NET 2.8.2.1 - Eco Theme by n3o Web Designers