[读书笔记]高性能JS-编程实践

本文探讨了JavaScript编程中的一些关键优化技巧,包括避免双重评估、使用字面量、消除重复工作等,旨在提升代码效率与可维护性。

This part is some example to practice.

1 avoid double evaluation

less use of eval,new Function,settimeout,setinterval.

string in these method are executable js code.when use these method,js will 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 two are 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

function addEvent(obj,type,handler){
    if(obj.addEventListener){
        obj.addEventListener(type,handler,false)
    }else{
        obj.attachEvent('on'+type,handler);
    }
}
function removeEvent(obj,type,handler){
    if(obj.removeEventListener){
        obj.removeEventListener(type,handler,false)
    }else{
        obj.detachEvent('on'+type,handler);
    }
}
when called ,function will do repeated job for check which browser we using. actually ,one test is enough.

one way 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 will override the past one.so next time called,it save lots of time.

and another way 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 way.






转载于:https://www.cnblogs.com/wz0107/p/4957416.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值