[Reading notes] High performance js-programming practice

Source: Internet
Author: User

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

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.