using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO; /// <summary>
/// 提供压缩 JavaScript 代码的能力。
/// </summary>
public sealed class JavaScriptMinifier
{
#region 私有字段 private const int EOF = -1; private readonly StringBuilder _JsBuilder;
private readonly TextReader _JsReader;
private int _TheA = Convert.ToInt32('\n');
private int _TheB;
private int _TheLookahead = EOF; #endregion #region 构造函数 /// <summary>
/// 初始化 <see cref="JavaScriptMinifier"/> 类的新实例。
/// </summary>
/// <param name="jsReader">包含要压缩的 JavaScript 代码的 <see cref="TextReader"/>。</param>
private JavaScriptMinifier(TextReader jsReader)
{
if (jsReader == null) throw new ArgumentNullException("jsReader"); this._JsReader = jsReader;
this._JsBuilder = new StringBuilder();
} #endregion #region 静态方法 /// <summary>
/// 压缩指定的 JavaScript 代码。
/// </summary>
/// <param name="js">包含要压缩的 JavaScript 代码的 <see cref="StringBuilder"/>。</param>
/// <returns>返回包含压缩后的 JavaScript 代码的 <see cref="StringBuilder"/>。</returns>
public static StringBuilder Minify(StringBuilder js) { return Minify(new StringReader(js.ToString())); } /// <summary>
/// 压缩指定的 JavaScript 代码。
/// </summary>
/// <param name="jsCode">要压缩的 JavaScript 代码。</param>
/// <returns>返回包含压缩后的 JavaScript 代码的 <see cref="StringBuilder"/>。</returns>
public static StringBuilder Minify(string jsCode) { return Minify(new StringReader(jsCode)); } /// <summary>
/// 压缩指定的 JavaScript 代码。
/// </summary>
/// <param name="jsReader">包含要压缩的 JavaScript 代码的 <see cref="TextReader"/>。</param>
/// <returns>返回包含压缩后的 JavaScript 代码的 <see cref="StringBuilder"/>。</returns>
public static StringBuilder Minify(TextReader jsReader)
{
JavaScriptMinifier jsmin = new JavaScriptMinifier(jsReader); jsmin._Jsmin(); return jsmin._JsBuilder;
} #endregion #region 私有方法 private void _Jsmin()
{
this._Action(3); while (this._TheA != EOF)
{
switch ((Char)this._TheA)
{
case ' ':
if (_IsAlphanum(this._TheB)) this._Action(1);
else this._Action(2); break;
case '\n':
switch ((Char)this._TheB)
{
case '{':
case '[':
case '(':
case '+':
case '-':
this._Action(1); break;
case ' ':
this._Action(3); break;
default:
if (_IsAlphanum(this._TheB)) this._Action(1);
else this._Action(2); break;
} break;
default:
switch ((Char)this._TheB)
{
case ' ':
if (_IsAlphanum(this._TheA))
{
this._Action(1); break;
} this._Action(3); break;
case '\n':
switch ((Char)this._TheA)
{
case '}':
case ']':
case ')':
case '+':
case '-':
case '"':
case '\'':
this._Action(1); break;
default:
if (_IsAlphanum(this._TheA)) this._Action(1);
else this._Action(3); break;
} break;
default:
this._Action(1); break;
} break;
}
}
} private void _Action(int d)
{
if (d <= 1) this._Put(this._TheA);
if (d <= 2)
{
this._TheA = this._TheB; if (this._TheA == '\'' || this._TheA == '"')
{
for (; ; )
{
this._Put(this._TheA);
this._TheA = this._Get(); if (this._TheA == this._TheB) break;
if (this._TheA <= '\n') throw new Exception(string.Format("Error: JSMIN unterminated string literal: {0}", this._TheA));
if (this._TheA != '\\') continue; this._Put(this._TheA);
this._TheA = this._Get();
}
}
} if (d > 3) return; this._TheB = this._Next(); if (this._TheB != '/' || ((((((((((((this._TheA != '(' && this._TheA != ',') && this._TheA != '=') && this._TheA != '[') && this._TheA != '!') && this._TheA != ':') && this._TheA != '&') && this._TheA != '|') && this._TheA != '?') && this._TheA != '{') && this._TheA != '}') && this._TheA != ';') && this._TheA != '\n')) return; this._Put(this._TheA);
this._Put(this._TheB); for (; ; )
{
this._TheA = this._Get(); if (this._TheA == '/') break; if (this._TheA == '\\')
{
this._Put(this._TheA);
this._TheA = this._Get();
}
else if (this._TheA <= '\n') throw new Exception(string.Format("Error: JSMIN unterminated Regular Expression literal : {0}.", this._TheA)); this._Put(this._TheA);
} this._TheB = this._Next();
} private int _Next()
{
int c = this._Get();
const int s = (int)'*'; if (c == '/')
{
switch ((Char)this._Peek())
{
case '/':
for (; ; )
{
c = this._Get(); if (c <= '\n') return c;
}
case '*':
this._Get(); for (; ; )
{
switch (this._Get())
{
case s:
if (this._Peek() == '/')
{
this._Get(); return Convert.ToInt32(' ');
} break;
case EOF:
throw new Exception("Error: JSMIN Unterminated comment.");
}
}
default:
return c;
}
} return c;
} private int _Peek()
{
this._TheLookahead = this._Get(); return this._TheLookahead;
} private int _Get()
{
int c = this._TheLookahead;
this._TheLookahead = EOF; if (c == EOF) c = this._JsReader.Read(); return c >= ' ' || c == '\n' || c == EOF ? c : (c == '\r' ? '\n' : ' ');
} private void _Put(int c) { this._JsBuilder.Append((char)c); } private static bool _IsAlphanum(int c) { return ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || c == '_' || c == '$' || c == '\\' || c > 126); } #endregion
}

JavaScriptMinifier

JavaScriptMinifier C#压缩Javascript的更多相关文章

  1. node.js 使用 UglifyJS2 高效率压缩 javascript 文件

    UglifyJS2 这个工具使用很长时间了,但之前都是在 gulp 自动构建 时用到了 UglifyJS 算法进行压缩. 最近玩了一下 UglifyJS2 ,做了一个 在线压缩javascript工具 ...

  2. 使用Ant命令压缩JavaScript文件

    压缩JavaScript文件可以减少代码尺寸,保护源代码,节省网络带宽,加快页面打开速度,甚至优化JS代码.Yahoo有一个压缩JS的工具叫做YUI compressor, Google也有一个工具叫 ...

  3. YUI Compressor 压缩 JavaScript 原理-《转载》

    YUI Compressor 压缩 JavaScript 的内容包括: 移除注释 移除额外的空格 细微优化 标识符替换(Identifier Replacement) YUI Compressor包括 ...

  4. 压缩javascript文件方法

    写在前面的话:正式部署前端的时候,javascript文件一般需要压缩,并生成相应的sourcemap文件,对于一些小型的项目开发,这里提供一个简单的办法. ======正文开始====== 1.下载 ...

  5. gzip压缩JavaScript

    为了提高客户端的体验效果,RIA开发逐渐兴起.这样会项目中会充斥的大量的JavaScript代码,与此同时会消耗客户端浏览器性能.对于 Ext 实现的 one page one application ...

  6. Grunt 使用(二)uglify插件压缩javascript代码

    本文在配置grunt基本环境的基础下,讲解如何使用grunt-contrib-uglify进行javascript压缩 本文只介绍了grunt-contrib-uglify插件的一种压缩方式适用于大部 ...

  7. 使用jsmin压缩javascript脚本

    官方地址:http://www.crockford.com/javascript/jsmin.html 点击页下方的”zip file containing an MS-DOS.exe file“下载 ...

  8. 使用Google Closure Compiler高级压缩Javascript代码

    背景 前端开发中,特别是移动端,Javascript代码压缩已经成为上线必备条件. 如今主流的Js代码压缩工具主要有: 1)Uglify http://lisperator.net/uglifyjs/ ...

  9. 使用Google Closure Compiler高级压缩Javascript代码注意的几个地方

    介绍 GCC(Google Closure Compiler)是由谷歌发布的Js代码压缩编译工具.它可以做到分析Js的代码,移除不需要的代码(dead code),并且去重写它,最后再进行压缩. 三种 ...

随机推荐

  1. locals()函数访问当前还在作用范围内的局部变量

    >>> element = 'silver' >>> number = 47 >>> 'Element {number} is {element} ...

  2. WebsitePanel 2.1.0beta配置部分

    到http://www.websitepanel.net/downloads/下载好单独安装包作为网站内容运行在IIS7.0上,配置applicationpool为localsystem Websit ...

  3. 初探appium之appium的使用

    上一篇中已经讲了python+appium的环境搭建.这里简单的讲一下appium的使用. 我也是第一次使用appium,看了教程问了人.知道appium可以通过模拟也可以连接上手机使用.本篇中,先使 ...

  4. python-appium手机自动化测试(仅需安装包)前期准备(pydev-eclipse编辑器)

    1.jdk安装与环境变量配置教程http://jingyan.baidu.com/article/6dad5075d1dc40a123e36ea3.html 我本机安装的是1.6.043 2.sdk下 ...

  5. PL/0与Pascal-S编译器程序详细注释

    学校编译课的作业之一,要求阅读两个较为简单的编译器的代码并做注释, 个人感觉是一次挺有意义的锻炼, 将自己的心得分享出来与一同在进步的同学们分享. 今后有时间再做进一步的更新和总结,其中可能有不少错误 ...

  6. 为什么你不应该自行更新 Drupal 网站?

    (译注:这篇文章主要还是针对于非专业人员及个人Drupal站长,对于专业的 Drupal 团队和公司而言 Drupal 的升级更新都有规范的操作流程,完全是家常便饭,不可能出现文中出现的这些情况.尽管 ...

  7. MSP430F149学习之路——按键

    代码一: /********************************** 程序功能:用按键控制LED灯熄灭 ***********************************/ #incl ...

  8. mysql中data_format用法

    date_format(date,format)可以把日期转换为制定的格式: mysql> select date_format('2008-08-08 22:23:00', '%W %M %Y ...

  9. 学习资料 50个常用的sql语句

    Student(S#,Sname,Sage,Ssex) 学生表 Course(C#,Cname,T#) 课程表 SC(S#,C#,score) 成绩表 Teacher(T#,Tname) 教师表 问题 ...

  10. 学习练习 java 实例属性 静态属性

    package com.hanqi; public class Test11Car11 { //静态 //实例属性 private int m = 0; //静态属性 //所有实例共有的,在内存里只有 ...