This was some example to practice.
1 Avoid double evaluation
Less use of eval,new function,settimeout,setinterval.
String in these method was executable JS Code.when use these method,js would execute code twice, first is normal js,second is JS code in string, such as Var a=eval (' 1+2 '); first asignment,second run code in string ' 1+2 ';
In Normal,don ' t use new Function. Try to use function instead of string both in Serttimeout and setinterval;
2 use literal;
var obj={
' A ': 1,
"B": 2
}
var arr=[1,2,3,4]
These good and run fast than something as
var obj={};
Obj.a=1;
obj.b=2;
3 No repeated job
Normally, we addevent use the function as
functionaddevent (obj,type,handler) {if(Obj.addeventlistener) {Obj.addeventlistener (Type,handler,false) }Else{obj.attachevent (' On ' +Type,handler); }}functionremoveevent (obj,type,handler) {if(Obj.removeeventlistener) {Obj.removeeventlistener (Type,handler,false) }Else{obj.detachevent (' On ' +Type,handler); }}
When called, function would do repeated the job for check which browser we using. Actually, one test is enough.
One-to-avoid is lazy load.
function Addevent (Obj,type,handler) {
if (Obj.addeventlistener) {
addevent= function (Obj,type,handler) {
Obj.addeventlistener (Type,handler,false)
}
}else{
addevent= function (Obj,type,handler) {
Obj.attachevent (' on ' +type,handler);
}
}
Addevent (Obj,type,handler)
}
Call this method Once,and new addevent would override the past one.so next time called,it save lots of time.
And another is conditional load.
var addevent=document.body.addeventlistener?
function (Obj,type,handler) {
Obj.addeventlistener (Type,handler,false)
}: Function (Obj,type,handler) {
Obj.attachevent (' on ' +type,handler);
}
Cool.
[Reading notes] High performance js-programming practice