skb
skb

Reputation: 31084

How do I write JavaScript which is compression-friendly?

I want to minimize the size of the Javascript code I have to send over the wire for my personal website. Are there any tricks to writing code that will compress better? I'm thinking about both min-ification and gzip.

Do I need to use short variable names? Or can min-ification just find all instances of those and shorten them? Or is it fine because gzip will detect them and compress over the wire? For functions, is it better to pass in an object with properties? Or just have individual parameters for each value needed? (I can imagine that parameters would be safe for min-ification to shorten because they are always local to the function)

I have a cursory understanding of what these tools do, but it's not enough to be confident in how I should write my Javascript to compress as small as possible.

Upvotes: 3

Views: 270

Answers (2)

Omri Sivan
Omri Sivan

Reputation: 339

You should use both minification and gzipping, see https://css-tricks.com/the-difference-between-minification-and-gzipping/ for some results. You should also consider using client side caching, as this will eliminate over the wire cost altogether on cache hits. Also make sure you're not sending any redundant http headers on your response.

Upvotes: 1

ncardeli
ncardeli

Reputation: 3492

If you are using a minification tool, you don't need to use short names for your variables, the minifier will take care of that.

As for function arguments, from a minification point of view, it's better to use individual parameters instead of object properties, because the minifier can't rename object properties, but will rename the parameters.

I don't feel qualified to advise you on how to write more compressable code from a Gzip point of view, but I can give you some advice on writing more minifiable Javascript code.

My first advice is that you run your favorite minifier on your code and then compare the pretty printed version of it, with the original code. That way you will learn what kind of changes your minifier makes on your code.

Usually, minifiers rename variables an function names to shorter ones, but can't rename object properties.

So avoid this:

foo.bar.baz.A = 1;
foo.bar.baz.B = 2;
foo.bar.baz.C = 3;

And instead, do this:

var shortcut = foo.bar.baz;
shortcut.d = 1;
shortcut.e = 2;
shortcut.f = 3;

A minifier will rename shortcut to a one or two letters variable.

Another good practice is using method chaining as much as possible (specially if you are using JQuery)

For example, avoid this:

$div.css('background', 'blue');  // set BG
$div.height(100);                // set height
$div.fadeIn(200);                // show element

And do this instead:

$('#my-div')
  .css('background', 'blue')
  .height(100)
  .fadeIn(200);

Upvotes: 1

Related Questions