欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

通过Java压缩JavaScript代码实例分享

程序员文章站 2024-02-24 19:12:52
通过移除空行和注释来压缩 javascript 代码 /** * this file is part of the echo web application...

通过移除空行和注释来压缩 javascript 代码

/**
 * this file is part of the echo web application framework (hereinafter \"echo\").
 * copyright (c) 2002-2009 nextapp, inc.
 *
 * compresses a string containing javascript by removing comments and whitespace.
 */
public class javascriptcompressor {
	private static final char line_feed = \'\\n\';
	private static final char carriage_return = \'\\r\';
	private static final char space = \' \';
	private static final char tab = \'\\t\';
	/**
   * compresses a string containing javascript by removing comments and 
   * whitespace.
   * 
   * @param script the string to compress
   * @return a compressed version
   */
	public static string compress(string script) {
		javascriptcompressor jsc = new javascriptcompressor(script);
		return jsc.outputbuffer.tostring();
	}
	/** original javascript text. */
	private string script;
	/** 
   * compressed output buffer.
   * this buffer may only be modified by invoking the <code>append()</code>
   * method.
   */
	private stringbuffer outputbuffer;
	/** current parser cursor position in original text. */
	private int pos;
	/** character at parser cursor position. */
	private char ch;
	/** last character appended to buffer. */
	private char lastappend;
	/** flag indicating if end-of-buffer has been reached. */
	private boolean endreached;
	/** flag indicating whether content has been appended after last identifier. */
	private boolean contentappendedafterlastidentifier = true;
	/**
   * creates a new <code>javascriptcompressor</code> instance.
   * 
   * @param script
   */
	private javascriptcompressor(string script) {
		this.script = script;
		outputbuffer = new stringbuffer(script.length());
		nextchar();
		while (!endreached) {
			if (character.isjavaidentifierstart(ch)) {
				renderidentifier();
			} else if (ch == \' \') {
				skipwhitespace();
			} else if (iswhitespace()) {
				// compress whitespace
				skipwhitespace();
			} else if ((ch == \'\"\') || (ch == \'\\\'\')) {
        // handle strings
        renderstring();
      } else if (ch == \'/\') {
        // handle comments
        nextchar();
        if (ch == \'/\') {
          nextchar();
          skiplinecomment();
        } else if (ch == \'*\') {
          nextchar();
          skipblockcomment();
        } else {
          append(\'/\');
        }
      } else {
        append(ch);
        nextchar();
      }
    }
  }
  /**
   * append character to output.
   * 
   * @param ch the character to append
   */
  private void append(char ch) {
    lastappend = ch;
    outputbuffer.append(ch);
    contentappendedafterlastidentifier = true;
  }
  /**
   * determines if current character is whitespace.
   * 
   * @return true if the character is whitespace
   */
  private boolean iswhitespace() {
    return ch == carriage_return || ch == space || ch == tab || ch == line_feed;    
  }
  /**
   * load next character.
   */
  private void nextchar() {
    if (!endreached) {
      if (pos < script.length()) {
        ch = script.charat(pos++);
      } else {
        endreached = true;
        ch = 0;
      }
    }
  }
  /**
   * adds an identifier to output.
   */
  private void renderidentifier() {
    if (!contentappendedafterlastidentifier)
      append(space);
    append(ch);
    nextchar();
    while (character.isjavaidentifierpart(ch)) {
      append(ch);
      nextchar();
    }
    contentappendedafterlastidentifier = false;
  }
  /**
   * adds quoted string starting at current character to output.
   */
  private void renderstring() {
    char startch = ch; // save quote char
    append(ch);
    nextchar();
    while (true) {
      if ((ch == line_feed) || (ch == carriage_return) || (endreached)) {
        // javascript error: string not terminated
        return;
      } else {
        if (ch == \'\\\\\') {
          append(ch);
          nextchar();
          if ((ch == line_feed) || (ch == carriage_return) || (endreached)) {
            // javascript error: string not terminated
            return;
          }
          append(ch);
          nextchar();
        } else {
          append(ch);
          if (ch == startch) {
            nextchar();
            return;
          }
          nextchar();
        }
      }
    }
  }
  /**
   * moves cursor past a line comment.
   */
  private void skiplinecomment() {
    while ((ch != carriage_return) && (ch != line_feed)) {
      if (endreached) {
        return;
      }
      nextchar();
    }
  }
  /**
   * moves cursor past a block comment.
   */
  private void skipblockcomment() {
    while (true) {
      if (endreached) {
        return;
      }
      if (ch == \'*\') {
        nextchar();
        if (ch == \'/\') {
          nextchar();
          return;
        }
      } else
        nextchar();
    }
  }
  /**
   * renders a new line character, provided previously rendered character 
   * is not a newline.
   */
  private void rendernewline() {
    if (lastappend != \'\\n\' && lastappend != \'\\r\') {
      append(\'\\n\');
    }
  }
  /**
   * moves cursor past white space (including newlines).
   */
  private void skipwhitespace() {
    if (ch == line_feed || ch == carriage_return) {
      rendernewline();
    } else {
      append(ch);
    }
    nextchar();
    while (ch == line_feed || ch == carriage_return || ch == space || ch == tab) {
      if (ch == line_feed || ch == carriage_return) {
        rendernewline();
      }
      nextchar();
    }
  }
}

总结

以上就是本文关于通过java压缩javascript代码实例分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!