Compression tools JSEncoder javascript script implementation (change)

2010-05-05  来源:本站原创  分类:Web  人气:224 

javascript script to achieve compression tool JSEncoder

2008-4-19 21:33:30 has been read: <script src="/hits.asp?ID=6952"> </ script> 310 comments

1, the algorithm works:
Javascript extract script file from word into the dictionary table, where use | separated string, then the corresponding word number (similar to the base64 encoded value) to write the original code in place, the formation of the compressed js code

2, the compression efficiency:
jquery-1.2.3.js the original file size of 95kb-> [other tools handle, remove the carriage returns, comments, etc.] jquery-1.2.3.min.js, size 53kb
=> This tool compressed: 32kb

3, optional other tools:
JSA 2.0 pre-alpha: http://sourceforge.net/project/showfiles.php?group_id=175776
packer: http://dean.edwards.name/packer/

4 download (including source code in the jar file)
2008.4 Ver: 0.5 Download

5, source code
java code below, finish the code only to find it is JSA (http://sourceforge.net/project/showfiles.php?group_id=175776) compression algorithm is implemented again, but if the author did not open source,
This counted as a technical study.
By jquery-1.2.3.min.js http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.2.3.min.js
Compression tested, compression rate> 40%.

1package com.cngd.jstool;
2
3import java.io.FileReader;
4import java.io.BufferedReader;
5import java.io.FileOutputStream;
6import java.io.IOException;
7import java.util.regex.Matcher;
8import java.util.regex.Pattern;
9import java.util.Vector;
10import java.text.DecimalFormat;
11
12 / ** *//**
13 * JSEncoder Script Compression Tools
14 * <p/>
15 * found that after finishing the code is JSA (http://sourceforge.net/project/showfiles.php?group_id=175776) compression algorithm and then to achieve
16 * file for jquery-1.2.3.min.js compression ratio results of this comparison are as follows
17 * ------------------------------------------------ -------------------
18 * Original Size | JSEncoder | JSA-20071021 (2.0 pre-alpha) | jquery packer algorithm
19 * ------------------------------------------------ -------------------
20 * 53kb | 32kb | 29kb | 29kb
21 * ------------------------------------------------ -------------------
22 * because the JSA further compression of local variables, so compared to smaller
23 * <p/>
24 * <p/>
25 * <p/>
26 * User: (on the road http://www.cnblogs.com/midea0978)
27 * Date: 2008-4-18
28 * Version: 0.5
29 * /
30public class JSEncoder (
31 public static final String ENCODE_BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
32 public boolean isDebug = false;
33
34 / ** *//**
35 * @ param filename js filename
36 * @ param offset offset> = 0 specify the offset variable, different code table position can be achieved offset the change, the smaller the offset receive greater compression ratio
37 * @ return the compressed code
38 * /
39 public String encode (String filename, int offset) throws Exception (
40 String jscript = readFileData (filename);
41 int size = jscript.length ();
42 jscript = jscript.replaceAll ("\ n", "");
43 / / replace \ -> \ \
44 jscript = jscript.replaceAll ("\ \ \ \", "\ \ \ \ \ \ \ \");
45 / / replace the single quote '=> \'
46 jscript = jscript.replaceAll ("\ \ '", "\ \ \ \ \ \'");
47
48 Pattern p = Pattern.compile ("([\ \ w \ \ ]+)");
49 Matcher m = p.matcher (jscript);
50 String element;
51 Vector <String> dict = new Vector <String> ();
52 int index;
53 StringBuffer encscript = new StringBuffer ();
54 StringBuffer dicttab = new StringBuffer ();
55
56 debugInfo ("===== coding dictionary mapping table =====");
57 while (m.find ()) (
58 element = m.group (1). Trim ();
59 if (! Dict.contains (element)) (
60 dict.add (element);
61 index = dict.size () - 1;
62) else (
63 index = dict.indexOf (element);
64)
65 debugInfo (index + "==>" + element);
66 m.appendReplacement (encscript, Base64Encode (offset + index + 1));
67)
68 for (String o: dict) dicttab.append (o + "|");
69 m.appendTail (encscript);
70 debugInfo ("===== end ====="); coding dictionary
71 debugInfo ("Offset =" + offset + ", the dictionary size =" + dict.size ());
72 debugInfo ("compressed code: \ n" + encscript.toString ());
73 String dictstr = dicttab.substring (0, dicttab.length () - 1). ToString ();
74 debugInfo ("dictionary string: \ n" + dictstr);
75 String res = formatCode (encscript.toString (), dictstr, dict.size (), offset);
76 int packsize = res.length ();
77 DecimalFormat df = new DecimalFormat ("######. 0 ");
78 System.out.println ("\ n original file size:" + size + "\ n compressed file size:" + packsize);
79 System.out.println ("================= \ n Compression ratio: "+ df.format ((size - packsize) * 100.0 / size) +"% " );
80 return res;
81)
82
83 private String readFileData (String filename) throws IOException (
84 BufferedReader in = new BufferedReader (new FileReader (filename));
85 StringBuffer sb = new StringBuffer ();
86 while (in.ready ()) (
87 sb.append (in.readLine () + "\ n");
88)
89 in.close ();
90 return sb.toString ();
91)
92
93 private void debugInfo (String txt) (
94 if (isDebug) System.out.println (txt);
95)
96
97 public static void main (String [] args) (
98 System.out.println ("JSEncoder 0.5 by midea0978 2008.4");
99 System.out.println ("=====================================");
100 System.out.println ("http://www.cnblogs.com/midea0978 \ n");
101 if (args.length <2) (
102 System.out.println ("Usage: java JSEncoder.jar jsfile outputfile [offset ].");
103 System.exit (0);
104)
105 try (
106 System.out.println ("input file:" + args [0]);
107 System.out.println ("output file:" + args [1]);
108 JSEncoder util = new JSEncoder ();
109 int offset = args.length> = 3? Integer.parseInt (args [2]): 0;
110 String code = util.encode (args [0], offset);
111 FileOutputStream fs = new FileOutputStream (args [1]);
112 fs.write (code.getBytes ());
113 fs.close ();
114) catch (Exception e) (
115 e.printStackTrace ();
116)
117)
118
11.9 / ** *//**
120 * Base64 decoding simulation
121 *
122 * @ param c the number to be encoded
123 * @ return code value
124 * /
125 private String Base64Encode (int c) throws Exception (
126 String res;
127 if (c <0) throw new Exception ("Error: Offset must be> = 0.");
128 if (c> 63)
129 res = Base64Encode (c>> 6) + Base64Encode (c & 63);
130 else (
131 / / method to use with appendReplacement will replace \
132 res = c == 63? "\ \": String.valueOf (ENCODE_BASE64.charAt (c));
133)
134 return res;
135)
136
137 private String formatCode (String enc, String dict, int size, int offset) (
138 StringBuffer str = new StringBuffer ();
139 str.append ("/ * Compressed by JSEncoder * / \ neval (function (E, I, A, D, J, K, L, H) (function C (A) (return A <62? String.fromCharCode ( A + = A <26? 65: A <52? 71: -4): A <63 ?'_': A <64?'': C (A>> 6) + C (A & 63)) while (A> 0) K [C (D -)] = I [- A]; function N (A) (return K [A] == L [A]? A: K [A]) if (''. replace (/^/, String)) (var M = E.match (J), B = M [0], F = E.split (J), G = 0; if (E.indexOf (F [0]) ) F =['']. concat (F); do (H [A + +] = F [G + +]; H [A + +] = N (B)) while (B = M [G]); H [A + +] = F [G ]||''; return H.join ('')} return E.replace (J, N )}(");
140 str.append ("'" + enc + "',");
141 str.append ("'" + dict + "'. Split ('|'),");
142 str.append (size + "," + (size + offset) + ", / [\ \ w \ \] + / g, (), (), []))");
143 return str.toString ();
144)
145
146)
147

相关文章
  • Compression tools JSEncoder javascript script implementation (change) 2010-05-05

    javascript script to achieve compression tool JSEncoder 2008-4-19 21:33:30 has been read: <script src="/hits.asp?ID=6952"> </ script> 310 comments 1, the algorithm works: Javascript extract script file from word into the dictionary t

  • Using javascript / css implementation GridView alternate row background color. Click the line color 2009-06-20

    Using javascript / css implementation GridView alternate row background color, click the line color Ask Bo a few days ago was found in someone clicks GridView question about the issue of line color, suddenly think of a long, long time ago, wrote an a

  • YUI Compressor js / css compression tools 2009-07-17

    YUI Compressor is provided by Julien Lecomte a Javascript compression tools. YUI Compressor using the Java language. Therefore needed for the operation of its Java Runtime Environment (version 1.4 or above) support. Usage: / / Compression JS java-jar

  • How to optimize the performance of JavaScript script: ShiningRay @ Nirvana Studio 2010-09-16

    With the development, speed and machine speed increase, more and more sites use a rich client technology. Ajax is now the most popular way. JavaScript is an interpreted language, it can not be achieved and the C / Java like the level of the client ca

  • JavaScript disabled dynamically change the properties of input 2011-05-14

    JavaScript disabled dynamically change the properties of input <body> <script language="javascript" type="text/javascript"> function enabledisable() { if(input.getAttribute('disabled')) { input.removeAttribute('disabled');

  • javascript java implementation of the Map (high) 2010-07-29

    javascript java implementation of the Map, the code is abroad on a website to see ( http://stackoverflow.com/questions/368280/javascript-hashmap-equivalent ), himself a minor modification, has also seen some before achieved with two arrays Map, but I

  • Image Compression Tools 2010-07-31

    Recently made an online mall project Need image compression on the Internet for a long time to find a good no fee is charged for some, simply wrote out a picture compression tools, but only part of the picture compression format of image formats jpg,

  • Introduce a javascript script compression tool, it looks like Ext is to use compressed 2010-11-02

    Basic Usage java-jar yuicompressor-2.4.2.jar ext-all-debug.js-o test.js Official points here: http://developer.yahoo.com/yui/compressor/ Tested one, ext-all-debug.js is compressed 75% of the water out, it seems bull fork. There is also a source, the

  • Daquan js form validation, form submission using JS control, javascript submit form (change) 2010-08-05

    1: js string length, determine the length of characters, js import restrictions, limiting not enter, textarea length limit 2.: Js judge character, to determine whether the character, can only enter characters 3: js determine whether the importation o

  • II. JavaScript script summary 2009-03-26

    Note that if you create the first in the target function has a name, age and a method myFunction, myFunction Ways are at similar method of constructing the definition for it. This approach has a drawbacks, in memory of these functions exist to create

  • oracle opatch the use of tools (oracle small patch installed) (change) 2010-05-30

    Starting from version 9.2, Oracle Corporation designed to achieve a specific patch installed management tools opatch.opatch using a A data structure called the inventory of the system (strictly be said to share with oui inventory), centralized manage

  • javascript XPath implementation 2010-06-06

    Knowledge of XPath, you can see http://www.w3school.com.cn/xpath/index.asp Note: The following code test environment FF3.6.3 and IE6.0. chrome browser is not tested, should not support. Before making XPath xml document should load. How to load can be

  • Mysql the transaction implementation (change) 2010-08-15

    transaction in the database programming is an important concept, which could control the operation of the database transaction commits. But to achieve in the program services, support services required database itself. Now the relational database, we

  • Java logging framework of a system design and implementation (change) 2010-03-29

    1 Introduction Log tracking system is an indispensable debugging tool, especially in the background of any unattended procedures and debugging environment for those who do not follow the system has wide application. For a long time, the log system as

  • JavaScript Inheritance Implementation 2010-06-11

    javasript is based on the prototype object implementation, inheritance, as follows: 1. Constructor is kept "private data" - in terms of examples. 2. Function prototype object prototype store "public" data and function 3. The child insi

  • javascript cookie implementation 2011-06-01

    <html> <head> <script type="text/javascript"> function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "=") if (c_start!=-1) { c_start=c_start + c_name.length+1 c_end=do

  • A directory with shell script to change the file suffix next class 2011-06-08

    This feature is mainly due to write my book can not view Hanwang. Asm,. Java and other file formats, so I need to put their Suffix changed to. Txt, but need to see things too much, simply write a program to solve! Write a java before use suffixes and

  • JavaScript Syntax Collection (change) 2010-03-29

    click () object. click () so that the object is clicked. closed object. closed the window whether the object is closed true / false clearTimeout (object) remove the object has been set setTimeout clearInterval (object) remove the object has been set

  • javascript XPath implementation [add] 2010-06-07

    In the last reference to "JavaScript Advanced Programming" Chapter 15, after doing some XPath knowledge for post-summary. Today they see the next w3c standards of API documentation can be found in the operation against the use of XPath as follow

  • Singleton separate mode java implementation (change) 2010-06-16

    Singleton separate model many opportunities for practical application. Recently ran into, so summed up under way. 1, the most common implementation is as follows: (does not support multi-threading) public class Singleton { private static Singleton si