How do I write JavaScript that's good for compression?

I want to minimize the size of the Javascript code I have to send via wire to my personal site. Are there any tricks for writing code that will compress better? I am thinking about minimal and gzip.

Should I use short variable names? Or can mining find all instances of these and cut them down? Or is this fine because gzip will detect them and compress over the wire? For functions, is it better to pass an object with properties? Or just have individual parameters for each value you need? (I can imagine the parameters would be safe to minify to shorten because they are always local to the function)

I have a cursory understanding of what these tools do, but it is not enough to be sure of how I should write my Javascript to compress as little as possible.

+3


source to share


2 answers


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

As far as function arguments, from a thumbnail point of view, it is better to use individual parameters instead of object properties, since minifier cannot rename object properties, but will rename parameters.

I don't feel competent to advise you to write more compressible code in terms of Gzip

, but I can give you some advice on writing more acceptable Javascript code.

My first piece of advice is that you run your favorite minifier in your code and then compare the rather printed version of it with the source code. This way you will know what changes your minifier will make to your code.

Usually minifiers rename variable function names to shorter ones, but cannot rename object properties.

So avoid this:

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

      

And do this instead:



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

      

A minifier will rename shortcut

one or two variable letters.

Another good practice is to use the chaining method as much as possible (especially 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);

      

+1


source


You have to 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 result in a complete exclusion from the total cost of cache wires. Also make sure that you are not sending redundant http headers in the response.



+1


source







All Articles