The speed of JavaScript code is divided into two parts: download time and execution speed.
Download time:
The Web browser downloads the JavaScript source code, that is, all the variable names and comments are included.
This and other factors increase the download time, which increases the overall time for script running and the download time.
The key factor is the number of bytes contained in the script.
Remember that a key number is 1160. It is best to keep every JavaScript file below 1160 bytes.
To obtain the optimal download time.
In a JavaScript file, each character is a byte. Therefore, each additional character (whether it is a variable name,
Function name, or comment) will affect the download speed.
1. delete comments
Any comments in the script should be deleted before deployment. during development, the comments are very important and can help the team
To understand the Code. However, to deploy the JavaScript code, annotations will obviously increase the size of the JavaScript code.
2. Delete tabs and spaces
Most of the excellent programmers will tighten the Code to increase readability. This is good, but the browser does not
These extra tabs and spaces are required, so it is best to delete them. Do not forget the function parameters, value assignment statements, and comparison.
Space between operations.
Copy to ClipboardReference: [www.bkjia.com] function doSomething (arg1, arg2, arg3) {alert (arg1 + arg2 + arg3 );}
Function doSomething (arg1, arg2, arg3) {alert (arg1 + arg2 + arg3 );}
The two lines are exactly the same for the JavaScript interpreter, although the first line is 12 bytes more than the second line.
Delete parameters. spaces between parentheses and separators in other languages can effectively reduce the overall size of the file.
Download time.
3. Delete all line breaks
Next, delete all linefeeds to reduce the script size. As long as you add a semicolon correctly at the end of each line of the program, no linefeeds are required.
4. Replace the variable name
This is the most boring method of optimization. Replacing the variable name is usually not done manually, because this process is not
Simple file search and replacement operations.
Copy to ClipboardReference: [www.bkjia.com] function doSomething (sName, sAge, sCity) {alert (sName + sAge + sCity );}
Function doSomething (a1, a2, a3) {alert (a1 + a2 + a3 );}
The first line of code above is original; the second line is replaced by the parameter name. This reduces 16 bytes. Imagine,
If the variable names in the script are replaced with two characters in length, how much will the length be saved?