Several places to note with Google Closure compiler advanced compression JavaScript code

Source: Internet
Author: User

Introduced

The GCC (Google Closure Compiler) is a JS code compression compilation tool released by Google. It can parse the JS code, remove the unwanted code (dead), and rewrite it, and then compress.

Three types of compression modes

GCC offers three compression modes:

1)Whitespace only2)Simple3)Advanced

Let's take this simple code as an example.

function sayHello(name) {  alert(‘Hello, ‘ + name);}sayHello(‘binnng‘);

Use these three compression modes respectively for compression:

whitespace only
function sayHello(name){alert("Hello, "+name)}sayHello("binnng");

Find just a simple strip wrapping comment.

Simple
function sayHello(a){alert("Hello, "+a)}sayHello("binnng");

The Whitespace only variable name of the local variable is shortened on the basis of the high-end point. This is also the compression method used by other compression tools, such as Uglify, is also the most mainstream compression method. More secure.

Advanced
alert("Hello, binnng");

Will find that the Advanced level of compression changes (destruction) of the original code structure, the direct output of the code final run results, it is true,,, 分析 重写 破坏 But the code compression to achieve the extreme, greatly reducing the amount of code.

Note the place

It is because GCC is such a destructive compression tool , so the use of unusually careful, slightly irregular may cause compression error or compression after successful but not normal operation. So, if you want to use Advanced level compression, what should you pay attention to?

All of the following unnamed levels of GCC compression are Advanced levels.

GCC also compresses the property name of the variable
var data = {  user: "binnng",  age: "18"};if ("user" in data) { alert(data.age);}

After uglify compression:

var data={user:"binnng",age:"18"};"user"in data&&alert(data.age);

After GCC compression:

var a={b:"binnng",a:"18"};"user"in a&&alert(a.a);

When GCC compression is found, the property name of the variable is shortened , the amount of code is reduced, but the problem is that the above GCC compressed code is actually not working correctly. Because the property name is shortened, data no longer has user a property named.

How to solve it?

var data = {  user: "binnng",  age: "18"};if (data.user) {  alert(data.age);}

This time again through GCC compression:

alert("18");

Direct output of the correct results.

If you do not want GCC to compress property names, such as when an AJAX request is sent to the backend interface, you can enclose the property name in double quotation marks:

var data = {  "user": "binnng",  "age": "18"};var ajax = function(url, data, callback) { (new window.XMLHttpRequest()).send(data); // ...}; ajax("//baidu.com", data, function(res) {console.log(res)});

This is done after GCC compression:

(new window.XMLHttpRequest).send({user:"binnng",age:"18"});

The parameter names required by the backend are retained intact.

Global variables to be explicitly mounted under window
var foo = "1234";alert(widnow.foo);

At this point, after GCC compression:

alert(window.a);

It's a little confusing. Because in gcc, the implicit global variable is no longer recognized , so the above code in the GCC eye foo is not attached to the window, so the following window.foo is actually undefined.

To resolve this problem, you must foo explicitly mount it under window:

window.foo = "1234";alert(widnow.foo);

After this has been compressed:

window.a="1234";alert(widnow.a);

At this time may be questioned, why not directly compressed into alert("1234") it? This is because GCC does not remove the variable that is mounted under window .

Export variable functions, if necessary
window.btnClick = function() {  alert("clicked");};

The above code is compressed and then becomes:

window.a=function(){alert("clicked")};

At this point, if the following code is present in the HTML, an error will be given.

<a onclick="btnClick()">点我</a>

You need to export the function at this time:

window["btnClick"] = function() { alert("clicked");};

After wrapping in double quotes, btnClick it is preserved. In the constructor, it is particularly important to note the export, for example:

var Animal = function(name) {  this.name = name;};Animal.prototype.eat = function() { alert(this.name + " is eating!");};

After the code has been compressed by GCC, nothing is left, because GCC believes that the code in the code is not executed, belongs to dead code . Since this is written, it must be needed, provided to others outside the call or something, this time need to export:

var Animal = function(name) {  this.name = name;};Animal.prototype.eat = function() { alert(this.name + " is eating!");};window["Animal"] = Animal;Animal.prototype["eat"]= Animal.prototype.eat;

After compression:

function a(b){this.name=b}a.prototype.a=function(){alert(this.name+" is eating!")};window.Animal=a;a.prototype.eat=a.prototype.a;

At this point, the Animal method was successfully preserved.

Also, it is JSONP important to export the callback method name when using the service-side data:

var jsonpCb = function() {  //...};getScript("/api/data?callback=jsonpCb");// 导出,否则jsonpCb会被压缩掉不能被识别window["jsonpCb"] = jsonpCb;
All business code Merge compression

a.js

var getName = function() {return "binnng"};

b.js

alert(getName());

If the individual compression a.js and b.js will be problematic, the result will be nothing a.js in, b.js the getName method is undefined ( undefined ). The right thing to do is to merge and compress the two.

Conclusion

GCC's high-level compression (advanced) is very powerful, the code compression is the ultimate, but its code writing requirements are more stringent, and destructive compression has been criticized by many developers.

But a little attention, strict norms of their own code style, understanding the principle of GCC compression, using good GCC advanced compression, will greatly reduce the volume of JS, thereby greatly improving the front-end code performance.

In addition, GCC, like other compression tools, also has Grunt , Gulp build components, can be very convenient to use it.

Original address: http://segmentfault.com/blog/laopopo/1190000002575760

Several places to note with Google Closure compiler advanced compression JavaScript code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.