Quantcast compress javascript code using .net

compress javascript code using .net

by Neon Quach 15. April 2010 02:55

Compress your JavaScript file by removing UN use code, or comment, whitespace, trim… to make it load faster in your web page is one of good work.

My last post which shows you how to compress css code to decrease file size
http://code2code.info/post/Efficient-stylesheet-minification-in-Net.aspx

and now, I will show all of you how to apply this technique for JavaScript.

 For the demo purpose, I will create console application using both C# and VB.NET

here is c# function:

/// <summary>
        /// Strips the whitespace from any .js file.
        /// </summary>
        private static string StripWhitespace(string content)
        {
            string[] lines = content.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            StringBuilder emptyLines = new StringBuilder();
            foreach (string line in lines)
            {
                string s = line.Trim();
                if (s.Length > 0 && !s.StartsWith("//"))
                    emptyLines.AppendLine(s.Trim());
            }
            content = emptyLines.ToString();
            // remove C styles comments
            content = Regex.Replace(content, "/\\*.*?\\*/", String.Empty, RegexOptions.Compiled | RegexOptions.Singleline);
            //// trim left
            content = Regex.Replace(content, "^\\s*", String.Empty, RegexOptions.Compiled | RegexOptions.Multiline);
            //// trim right
            content = Regex.Replace(content, "\\s*[\\r\\n]", "\r\n", RegexOptions.Compiled | RegexOptions.ECMAScript);
            // remove whitespace beside of left curly braced
            content = Regex.Replace(content, "\\s*{\\s*", "{", RegexOptions.Compiled | RegexOptions.ECMAScript);
            // remove whitespace beside of coma
            content = Regex.Replace(content, "\\s*,\\s*", ",", RegexOptions.Compiled | RegexOptions.ECMAScript);
            // remove whitespace beside of semicolon
            content = Regex.Replace(content, "\\s*;\\s*", ";", RegexOptions.Compiled | RegexOptions.ECMAScript);
            // remove newline after keywords
            content = Regex.Replace(content, "\\r\\n(?<=\\b(abstract|boolean|break|byte|case|catch|char|class|const|continue|default|delete|do|double|else|extends|false|
final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|long|native|new|null|package|
private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|
var|void|while|with)\\r\\n)"
, " ", RegexOptions.Compiled | RegexOptions.ECMAScript);
            content = Regex.Replace(content, @"[\n\r]+\s*", string.Empty); // space
            return content;
        }

VB.NET

Public Function StripWhitespace(ByVal content As String) As String
        Dim lines() = content.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
        Dim emptyLines As New StringBuilder()
        For Each line As String In lines
            Dim s = line.Trim()
            If s.Length > 0 AndAlso Not s.StartsWith("//") Then
                emptyLines.Append(s.Trim())
            End If
        Next
        content = emptyLines.ToString()
        ' remove C styles comments
        content = Regex.Replace(content, "/\*.*?\*/", [String].Empty, RegexOptions.Compiled Or RegexOptions.Singleline)
        content = Regex.Replace(content, "^\s*", [String].Empty, RegexOptions.Compiled Or RegexOptions.Multiline)
        content = Regex.Replace(content, "\s*[\r\n]", vbCr & vbLf, RegexOptions.Compiled Or RegexOptions.ECMAScript)
        ' remove whitespace beside of left curly braced
        content = Regex.Replace(content, "\s*{\s*", "{", RegexOptions.Compiled Or RegexOptions.ECMAScript)
        ' remove whitespace beside of coma
        content = Regex.Replace(content, "\s*,\s*", ",", RegexOptions.Compiled Or RegexOptions.ECMAScript)
        ' remove whitespace beside of semicolon
        content = Regex.Replace(content, "\s*;\s*", ";", RegexOptions.Compiled Or RegexOptions.ECMAScript)
        ' remove newline after keywords
        content = Regex.Replace(content, "\\r\\n(?<=\\b(abstract|boolean|break|byte|case|catch|char|class|const|continue|default|delete|do|double|else|extends|false|final|finally|
float|for|function|goto|if|implements|import|in|instanceof|int|interface|long|native|new|null|package|private|protected|public|
return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|var|void|while|with)\\r\\n)"
, " ", RegexOptions.Compiled Or RegexOptions.ECMAScript)
        content = Regex.Replace(content, "[\n\r]+\s*", String.Empty) ' space
        Return content
    End Function

Then I call this function in the Main

C#
static void Main(string[] args)
{
    string content = File.ReadAllText("../../blog.js");
    File.WriteAllText("../../blog-min.js", StripWhitespace(content));
    Console.Write("Press any key to continue!");
    Console.Read();
}

VB.NET

Sub Main()
        Dim content As String = File.ReadAllText("../../blog.js")
        File.WriteAllText("../../blog-min.js", StripWhitespace(content))
        Console.WriteLine("Press any key to continue!`")
        Console.Read()
End Sub


Done, now when you run this code, it will create a new file with compress content.

Tags: ,


Categories: javascript | c# | vb.net

blog comments powered by Disqus

About me

I'm  currently employed as Software developer at devinition.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

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