JavaScript optimization tips (file slimming) _javascript tips

Source: Internet
Author: User
has been studying Javascript-related technologies recently. The importance of optimizing JavaScript code is highlighted in a section of JavaScript advanced programming. It is believed that there are many Javascript developers who are more or less exposed to this type of problem while they are developing.

In most cases, code optimization is not a part of the actual development that needs to be focused on. But once the code is complete, developers always expect their code to be as short and efficient as possible. In combination with the knowledge gained from the book and the experience of my actual development process, the following shows some of the tricks I have taken (as a textbook).

Objective

In contrast to scripting languages, compiled languages do not need to be too concerned with optimization issues. To a large extent, the compile-time compiler will optimize the operation of the row. For example, all variables, functions, objects, and so on are replaced with symbols and pointers (which are commonly referred to as executables) that only the processor can understand. Other scripting languages don't need to be overly concerned with file size issues, but Javascript is different.
Because it first downloads the source code from the server side and then executes it by the client's browser. As a result, the speed of JavaScript code is split into two parts: Download time (depending on the size of the file) and execution speed (depending on the code algorithm). This main discussion is the download time optimization of JavaScript, which is how to minimize the capacity of the JavaScript file itself.
One of the numbers to remember here is 1160, which is the number of bytes that can be put into a single TCP/IP packet. So, the best expectation is to keep each Javascript file in 1160 bytes for optimal download time.

Delete a comment

This seems to be nonsense, but many developers will forget it. In the actual production environment, the annotations in the script should be deleted. Annotations are fairly important during development and can help the team understand the code. However, in a real production environment, annotations can significantly make script files larger. Removing them does not have any effect on the actual operation of the script.

Delete tabs and spaces

Code with good indents and spaces is usually good for readability. But browsers don't need these extra tabs and spaces, so it's a good idea to remove them. And, of course, don't forget the function arguments, assignment statements, and the spaces between comparison operations. Like what

function Showmethemoney (Money)
{
if (!money) {
return false;
} else {
...
}
can be optimized into

function Showmethemoney (Money) {if (!money) {reutrn false;} Else{...}}

This can reduce the partial capacity.

Delete all line Wraps

There's a lot of thinking about wrapping in Javascript, but the bottom line is to add more readability to the code. But excessive line-wrapping can also result in the increase of code volume.
You may not be able to delete a newline character for some reason, so that the file is in Unix format. Because the line breaks in Windows and MAC format wrap in two characters, Unix uses only one. So converting a file to a Unix format can also save a few bytes.

Replace variable name

This is probably the most boring practice, which is not usually done by hand. After all, the name of the variable is meaningless to the interpreter (it's just a bit friendlier for the developer), replacing a descriptive variable name in a production environment with a simpler, shorter name can also reduce a portion of the volume. For example, the above code can be reduced to:

function sm (m) {if (!m) {reutrn false;} Else{...}}

While this may seem like a headache, the actual effect is the same.

Working with tools

There may be some difficulty in actually using the method described above, but fortunately there are off-the-shelf external tools to complete these steps. Here are a few simple introductions:
ECMAScript cruncher:http://saltstorm.net/depo/esc/
Jsmin (The JavaScript minifier): http://www.crockford.com/javascript/jsmin.html
Online JavaScript compressor.:http://dean.edwards.name/packer/

I guess you'll be interested in reading this article.

Other methods

To replace a Boolean value

For comparison, true equals 1,false equals 0. As a result, the literal true of the script can be replaced with a substitution, and false can be replaced with 0来. 3 bytes are saved for true, and False saves 4 bytes.

Reduce negative detection

A statement that detects whether a value is valid is often found in code. Most of the conditions are not judged by whether a variable is undefined, null, or FALSE, for example:

if (myvalue!= undefined) {
// ...
}

if (myvalue!= null) {
// ...
}

if (MyValue!= false) {
// ...
}

These are all correct, but they can have the same effect with a logical non-operator:

if (!myvalue) {
// ...
}

Such substitutions can also save a fraction of the bytes.

Using arrays and object literals

This is better to understand, for example, two lines are the same:

var myarray = new Array;
var myarray = [];

However, the second line is much shorter than the first line and can be easily understood. Similarly, there are object declarations:


var myObject = new Object;
var myObject = {};

For example, the following statement:

var mySite = new Object;
Mysite.author = "Feelinglucky";
Mysite.location = "http://www.gracecode.com";

This can also be very easy to understand, and a lot shorter:

var mySite = {Author: "Feeinglucky", Location: "Http://www.gracecode.com"};

OK, this is the right time to be here. As mentioned above, the speed of Javascript code is split into two parts: Download time (depending on the size of the file) and execution speed (depending on the code algorithm). This is a discussion of the optimization of download time, the next phase of the discussion on the speed of the line optimization (so it looks very technical content, not mody).

Homework is arranged below. Maybe you'll be interested to know how jQuery is compressing its 70KB code to around 20KB.
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.