I. Importance of error handling
In the past, JavaScript was always well known for the emergence of strange and confusing error messages. debugging such information is indeed a painful experience.
Therefore, the fourth edition of the browser (ie4.0 and netscape4.0) contains some basic error handling functions. Shortly afterwards, ECMA and ecmascript proposed a new solution in the third edition.
The latest ecmascript adds an exception handling mechanism and uses a model transplanted from Java. The third edition uses some reserved words in the second edition of ecmascript to implement try... Catch... Finally structure and throw Operator
1.1 early browser error handling
Early browsers (such as ie3.0) do not handle errors. The function returns an invalid value (generally null, false, or-1, depending on different functions) to indicate an error. Consider the following code:
VaR Index = findcolor (colorarray, "Red ");
If (Index =-1)
Alert ("This item does not exist ");
Else
Alert ("the position of this item is:" + index );
The problem above is that the return value of the findcolor function-1 cannot be determined whether it is not found or error.
Error and error handling will help us solve this problem
After JavaScript introduces error handling, Web developers can better control the code. Good error handling technology makes the development, testing and deployment of scripts smoother. This is especially true for JS because it lacks a standard development environment to guide developers.
Ii. Errors and exceptions
There are two types of errors: syntax errors and runtime errors.
1. Syntax Error
Parsing errors occur during compilation in traditional programming languages and occur during interpretation in JavaScript. These errors are directly caused by unexpected characters in the code. Then it cannot be fully compiled/explained, for example:
Window. Alert ("test"
However, in Javascript, only the code in the same thread will be affected by the error code. Code in other threads and in other externally referenced files. If the Code does not depend on the code that contains the error, you can continue to execute
For example:
<Head>
<SCRIPT type = "text/JavaScript">
Function handlerload (){
Windows. Open ("about: blank ");
}
Function handleclick (){
Alert ("click ");
}
</SCRIPT>
</Head>
<Body onload = "handlerload ()">
<Input type = "button" value = "test" onclick = "handlerclick ()"/>
</Body>
This JS Code will report a JS error when loading the page, but will not affect the execution of handleclick.
Iii. handling errors
Javascript provides two special error handling methods.
Bom contains an onerror event processing function. Both the window object and the image object have
At the same time, ecmascript defines another try... Catch structure to handle exceptions
1. onerror event processing function
<Script language = "JavaScript">
<! --
Function handleerror (){
Alert ("Error ");
Return true;}
Window. onerror = handleerror ;//Blocking all error prompts is dangerous.
// -->
</SCRIPT>
</Head>
<Body onload = "handleload ()">
</Body>
</Html>
In this way, a message box with an error will pop up, but unfortunately the error prompt box will still pop up on the webpage.
If you want to remove this prompt box, the transformation is as follows:
} Function handleerror ()
}{
} Alert ("error ");
} Return true;
}}
2. Retrieve the error message
Onerror event processing functions provide three types of information to determine the exact nature of an error.
> Error message-the browser displays the same information for a given error
> URL-in which file an error occurred
> Row number-the row number of the error in the given URL
For example:<Script language = "JavaScript">
<! --
Function handleerror (smessage, Surl, Sline ){
Alert ("Error. \ n "+"Message: "+ smessage +" \ nurl: "+ Surl +
"\ NError row number: "+ Sline );
Return true ;}
Window. onerror = handleerror;
// -->
</SCRIPT>
// Customize our error message
Image loading error
Unlike window. onerror, the IMG onerror event processing function has no parameters for any additional messages.
If the image is not loaded properly, the onerror event is triggered.
The main problem with using the onerror event to process functions is that it is part of the BOM, so there is no standard to control their behavior. Therefore, any browser uses this event to handle errors in functions.
For example, when an error occurs in IE, normal code continues to be executed. All variables and data are retained and can be accessed through the onerror event processing function. However, in Mozilla, normal code execution ends, and all variables and data before error handling are destroyed.
In addition, its browser does not support onerror event processing functions on the window object, but both support onerror events on images.
Try... CatchStatement
The third edition of ecmascript supports try... Catch... Finally syntax
Basic Syntax:
Try {
// Code
} Catch ([Exception]) {
// Code
} [Finally {
// Code
}]
For example: <script language = "JavaScript">
<! --
Try {
Alert ("OK ");
} Catch (exception ){
Alert ("an error processed ");
} Finally {
Alert ("finally ");
}
Alert ("OK ");
// -->
</SCRIPT>
Note: Unlike Java, multiple catch statements are not supported, but nested catch statements are supported.
For example, try {var A = Document. getelementbyid ("txtuser ");
Alert (A. value );
} Catch (Ex ){
Alert ("error ");
}
For example, the detailed error message try {var A = Document. getelementbyid ("txtuser") is displayed ");
Alert (A. value );
} Catch (Ex ){
Alert (ex. Message); // Error
}
Try {var A = Document. getelementbyid ("txtuser ");
Alert (A. value );
} Catch (Ex)
{Try {
Alert (oexception. Message );}
Catch (Ex ){
Alert (ex. Message );}}
Iv. Error object
Similar to Java error base class exception, JavaScript has a base class error, which has the following characteristics:
P name-indicates a string of the Error Type
P message-actual error message
The error object name corresponds to its class and can be one of the following values:
1. evalerror: the error occurs in the eval () function.
2. rangeerror: the value of a number exceeds the range that can be expressed in JavaScript.
3. referenceerror: Invalid reference is used.
4. syntaxerror: A syntax error occurs in eval () function calls.
5. typeerror: the type of the variable is not expected
6. urierror: Error in the encodeuri () or decodeuri () function
Note: Both mozzilla and IE have extended error objects. For example, ie provides a number feature to indicate error codes, and description can also be used to replace message.
Error Type DeterminationTwo methods:
Method 1: identify by name attribute
Method 2: Use the instanceof Operator
For example, try {var scriptstr = "Var a = 0; var B = 1; var c = A ++ B; alert (c )";
Eval (scriptstr );
} Catch (Ex)
{If (ex instanceof syntaxerror)
{Alert ("syntax error ");}}
Throw an exception
Ecmascript also introduces throw statements for throwing an exception purposefully.
Syntax: Throw error_object
Error_object can be a string, number, Boolean value, or actual object. For example:
Throw "An error occurred ";
Throw 5007; throw true;
Throw new object ();
Throw new error ();
Throw new error ("error ");
Throw new error (10001, "error ");
Optimize Javascript
Javascript is downloaded as the source code, and then the browser explains it (there is no compilation problem). Therefore, the performance of JavaScript is reflected in the speed method, and the speed is divided into two parts: download time and execution speed
1. download time: using other languages such as Java, we do not have to consider variable names with a length of 100 characters and a large number of comments. because these names will be replaced after compilation and comments will be automatically deleted, but JavaScript developers will not be so cool!
The key factor to increase the download time is the number of bytes contained in the script.
Remember a key number 1160; this is the number of bytes that can be placed into a single TCP-IP package. It is recommended that each Javascript file be kept below 1160 bytes to obtain the optimal download time.
How to Reduce the download time:
Ü delete comments
Ü Delete tabs and spaces
Ü delete all line breaks
Ü replace variable name
For example, function dosomthing (sname, sage, scity)
=> Function dosomthing (A, B, C)
One recommended tool: ecmascript cruncher
: Http://www.saltstorm.net/depo/esc/
For example: C: \> cscript c: \ ESC-1.14 \ Esc. WSF-L [0-4]-Ow outputfile. js inputfile1.js [inputfile2.js]
Note:
Cscript is a Windows shell script interpreter.
[0-4] is a compression grade
-Ow indicates that the next parameter is the optimized output file name, and the last part is the JS file to be optimized.
ESC supports the following four optimization levels
Level |
Description |
0 |
Merge multiple files into a single file without changing the script |
1 |
Delete all comments |
2 |
Delete additional tabs and spaces except for one level. |
3 |
Delete the line feed except level 2. |
4 |
Replace variable names with three levels |
|
|
Other methods to reduce the number of bytes
Ü replace boolean values
For comparison, true is equal to 1, and false is equal to 0. Therefore, the literal values of true in the script can be replaced by 1, while false can be replaced by 0.
For example, VAR bfound = false;
For (VAR I = 0; I <atest. Length &&! Bfound; I ++)
{
Bfound = true;
}
Can be replaced:
VaR bfound = 0;
For (VAR I = 0; I <atest. Length &&! Bfound; I ++)
{
Bfound = 1;
}
Shorten negative detection
For example:
If (otest! = Undefined ){}
If (otest! = NULL ){}
Else if (otest! = False) {} If (! Otest) {// do something}
Ü use array and object literal
VaR atest = new array () ;=> var atest = []; // equivalent to creating an empty array
VaR otest = new object ();
Export otest = {};
For example:
VaR ocar = new object ();
Ocar. color = "red ";
Ocar. Name = "mycar ";
=>
VaR ocar = {color: "red", name: "mycar "}
} Execution time
1. Scope of attention
ÜUse local variables
If you directly use variables instead of using VARDeclare the variable in the windowWithin the range, the interpreter searches for the entire range tree.
For example: <script language = "JavaScript">
<! --
Function mytest ()
{
Svar = "micro ";
Alert (svar );
}
Mytest ();
Alert ("OK" + svar );
// -->
</SCRIPT>
} Avoid with statements
The smaller the range, the faster the speed. This is why the with statement is not used.
For example, alert (document. Title );
Alert (document. Body. tagname );
Alert (document... location );
Replace with: With (document)
{
Alert (title );
Alert (body. tagname );
Alert (location );
}
It is best to avoid using the with statement. The reduced code length cannot compensate for the performance loss.
} Computer science basics
Ü select the correct Algorithm
1. Reverse loop. speed required
For (VAR I = 0; I <avalues. length; I ++)
{}
=>
For (VAR I = avalues. length; I> = 0; I --)
{}
} Flip Loop
For example, VAR I = 0;
While (I <avalues. length)
{
I ++;
}
==>: Do {
I ++
} While (I> = 0)
Using VaR I = avalues. Length-1;
Do {
I --;
} While (I> = 0)
U others
Ü avoid string link and use your own Encapsulation Method
Ü use built-in methods first
Ü store common values
Ü save on Dom usage
(From: http://www.cnblogs.com/aqbyygyyga/archive/2011/10/29/2228824.html)