开发者

Good resources for extreme minified JavaScript (js1k-style)

开发者 https://www.devze.com 2023-01-27 09:19 出处:网络
As I\'m sure mo开发者_运维知识库st of the JavaScripters out there are aware, there\'s a new, Christmas-themed js1k. I\'m planning on entering this time, but I have no experience producing such minifie

As I'm sure mo开发者_运维知识库st of the JavaScripters out there are aware, there's a new, Christmas-themed js1k. I'm planning on entering this time, but I have no experience producing such minified code. Does anyone know any good resources for this kind of thing?


Google Closure Compiler is a good javascript minifier.

There is a good online tool for quick use, or you can download the tool and run it as part of a web site build process.


Edit: Added a non-exhaustive list of tricks that you can use to minify JavaScript extremely, before using a minifier:

Shorten long variable names
Use shortened references to built in variables like d=document;w=window.

Set Interval
The setInterval function can take either a function or a string. Pass in a string to reduce the number of characters used: setInterval('a--;b++',10). Note that passing in a string forces an eval invokation so it will be slower than passing in a function.

Reduce Mathematical Calculations
Example a=b+b+b can be reduced to a=3*b.

Use Scientific Notation
10000 can be expressed in scientific notation as 1E4 saving 2 bytes.

Drop leading Zeroes
0.2 = .2 saves a byte

Ternery Operator

if (a > b) {
     result = x;
}
else {
  result = y;
}

can be expressed as result=a>b?x:y

Drop Braces
Braces are only required for blocks of more than one statement.

Operator Precedence
Rely on operator precedence rather than adding unneeded brackets which aid code readability.

Shorten Variable Assignment
Rather than function x(){a=1,b=2;...}() pass values into the function, function x(a,b){...}(1,2)

Think outside the box
Don't automatically reach for standard ways of doing things. Rather than using d.getElementById('p') to get a reference to a DOM element, could you use b.children[4] where d=document;b=body.


Original source for above list of tricks:

http://thingsinjars.com/post/293/the-quest-for-extreme-javascript-minification/


Spolto is right.
Any code minifier won't do the trick alone. You need to first optimize your code and then make some dirty manual tweaks.

In addition to Spolto's list of tricks I want to encourage the use of logical operators instead of the classical if else syntax. ex:
The following code

if(condition){
    exp1;
}else{
    exp2;
}

is somewhat equivalent to

condition&&exp1||exp2;  

Another thing to consider might be multiple variable declaration :

var a = 1;var b = 2;var c = 1;

can be rewritten as :

var a=c=1,b=2;

Spolto is also right about the braces. You should drop them. But in addition, you should know that they can be dropped even for blocks of more expressions by writing the expressions delimited by a comma(with a leading ; of course) :

if(condition){
    exp1;
    exp2;
    exp3;
}else{
    exp4;
    exp5;
}

Can be rewritten as :

 if(condition)exp1,exp2,exp3;
 else exp4,exp5;

Although it's not much (it saves you only 1 character/block for those who are counting), it might come in handy. (By the way, the latest Google Closure Compiler does this trick too).

Another trick worth mentioning is the controversial with functionality.
If you care more about the size, then you should use this because it might reduce code size.
For example, let's consider this object method:

object.method=function(){
    this.a=this.b;
    this.c++;
    this.d(this.e);
}

This can be rewritten as :

object.method=function(){
    with(this){
        a=b;
        c++;
        d(e);
    }
}

which is in most cases signifficantly smaller.

Something that most code packers & minifiers do not do is replacing large repeating tokens in the code with smaller ones. This is a nasty hack that also requires the use of eval, but since we're in it for the space, I don't think that should be a problem. Let's say you have this code :

a=function(){/*code here*/}; 
b=function(){/*code here*/};
c=function(){/*code here*/};
/*...*/
z=function(){/*code here*/};

This code has many "function" keywords repeating. What if you could replace them with a single(unused) character and then evaluate the code?
Here's how I would do it :

eval('a=F(){/*codehere*/};b=F(){/*codehere*/};c=F(){/*codehere*/};/*...*/z=F(){/*codehere*/};'.replace(/function/g,'F'));

Of course the replaced token(s) can be anything since our code is reduced to an evaluated string (ex: we could've replaced =function(){ with F, thus saving even more characters).
Note that this technique must be used with caution, because you can easily screw up your code with multiple text replacements; moreover, you should use it only in cases where it helps (ex: if you only have 4 function tokens, replacing them with a smaller token and then evaluating the code might actually increase the code length :

var a = "eval(''.replace(/function/g,'F'))".length,
    b = ('function'.length-'F'.length)*4;
alert("you should" + (a<b?"":" NOT") + " use this technique!");


In the following link you'll find surprisingly good tricks to minify js code for this competition:

http://www.claudiocc.com/javascript-golfing/

One example: (extracted from section Short-circuit operators):

if (p) p=q;  // before
p=p&&q;      // after

if (!p) p=q; // before
p=p||q;      // after

Or the more essoteric Canvas context hash trick:

// before
a.beginPath
a.fillRect
a.lineTo
a.stroke
a.transform
a.arc                                  

// after
for(Z in a)a[Z[0]+(Z[6]||Z[2])]=a[Z];
a.ba
a.fc
a.ln
a.sr
a.to
a.ac

And here is another resource link with amazingly good tricks: https://github.com/jed/140bytes/wiki/Byte-saving-techniques


First off all, just throwing your code into a minifier won't help you that much. You need to have the extreme small file size in mind when you write the code. So in part, you need to learn all the tricks yourself.

Also, when it comes to minifiers, UglifyJS is the new shooting star here, its output is smaller than GCC's and it's way faster too. And since it's written in pure JavaScript it should be trivial for you to find out what all the tricks are that it applies.

But in the end it all comes down to whether you can find an intelligent, small solution for something that's awsome.


Also:

Dean Edwards Packer http://dean.edwards.name/packer/

Uglify JS http://marijnhaverbeke.nl/uglifyjs


A friend wrote jscrush packer for js1k.

Keep in mind to keep as much code self-similar as possible.

My workflow for extreme packing is: closure (pretty print) -> hand optimizations, function similarity, other code similarity -> closure (whitespace only) -> jscrush.

This packs away about 25% of the data.

There's also packify, but I haven't tested that myself.


This is the only online version of @cowboy's packer script:

http://iwantaneff.in/packer/

Very handy for packing / minifying JS

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号