Web程序员必备的7个JavaScript函数
数年前,只要我们编写JavaScript,都必须用到几个常用的函数,比如,addEventListener和attachEvent,并不是为了很超前的技术和功能,只是一些基本的任务,原因是各种浏览器之间的差异造成的。时间过去了这么久,技术在不断的进步,仍然有一些JavaScript函数是几乎所有Web程序员必备的,或为了性能,或为了功能。
防止高频调用的debounce函数
这个debounce函数对于那些执行事件驱动的任务来说是必不可少的提高性能的函数。如果你在使用scroll,resize,key*等事件触发执行任务时不使用降频函数,也行你就犯了重大的错误。下面这个降频函数debounce能让你的代码变的高效:
//返回一个函数,that,aslongasitcontinuestobeinvoked,willnot
//betriggered.Thefunctionwillbecalledafteritstopsbeingcalledfor
//Nmilliseconds.If`immediate`ispassed,triggerthefunctiononthe
//leadingedge,insteadofthetrailing.
functiondebounce(func,wait,immediate){
vartimeout;
returnfunction(){
varcontext=this,args=arguments;
varlater=function(){
timeout=null;
if(!immediate)func.apply(context,args);
};
varcallNow=immediate&&!timeout;
clearTimeout(timeout);
timeout=setTimeout(later,wait);
if(callNow)func.apply(context,args);
};
};
//Usage
varmyEfficientFn=debounce(function(){
//Allthetaxingstuffyoudo
},250);
window.addEventListener('resize',myEfficientFn);
这个debounce函数在给定的时间间隔内只允许你提供的回调函数执行一次,以此降低它的执行频率。当遇到高频触发的事件时,这样的限制显得尤为重要。
设定时间/频率循环检测函数
上面提到的debounce函数是借助于某个事件的触发。但有时候并没有这样的事件可用,那我们只能自己写一个函数来每隔一段时间检查一次。
functionpoll(fn,callback,err,timeout,interval){
varstartTime=(newDate()).getTime();
varpi=window.setInterval(function(){
if(Math.floor(((newDate).getTime()-startTime)/1000)<=timeout){
if(fn()){
callback();
}
}else{
window.clearInterval(pi);
err();
}
},interval)
}
禁止重复调用、只允许执行一次的once函数
很多时候,我们只希望某种动作只能执行一次,就像是我们使用onload来限定只在加载完成时执行一次。下面这个函数就能让你的操作执行一次后就不会再重复执行。
functiononce(fn,context){
varresult;
returnfunction(){
if(fn){
result=fn.apply(context||this,arguments);
fn=null;
}
returnresult;
};
}
//Usage
varcanOnlyFireOnce=once(function(){
console.log('Fired!');
});
canOnlyFireOnce();//"Fired!"
canOnlyFireOnce();//nada
这个once函数能够保证你提供的函数只执行唯一的一次,防止重复执行。
获取一个链接的绝对地址getAbsoluteUrl
获取链接的绝对地址并不像你想象的那么简单。下面就是一个非常实用的函数,能根据你输入的相对地址,获取绝对地址:
vargetAbsoluteUrl=(function(){
vara;
returnfunction(url){
if(!a)a=document.createElement('a');
a.href=url;
returna.href;
};
})();
//Usage
getAbsoluteUrl('/something');
这里使用了a标签href来生成完整的绝对URL,十分的可靠。
判断一个JavaScript函数是否是系统原生函数isNative
很多第三方js脚本都会在全局变量里引入新的函数,有些甚至会覆盖掉系统的原生函数,下面这个方法就是来检查是不是原生函数的:
;(function(){
//Usedtoresolvetheinternal`[[Class]]`ofvalues
vartoString=Object.prototype.toString;
//Usedtoresolvethedecompiledsourceoffunctions
varfnToString=Function.prototype.toString;
//Usedtodetecthostconstructors(Safari>4;reallytypedarrayspecific)
varreHostCtor=/^\[object.+?Constructor\]$/;
//Compilearegexpusingacommonnativemethodasatemplate.
//Wechose`Object#toString`becausethere'sagoodchanceitisnotbeingmuckedwith.
varreNative=RegExp('^'+
//Coerce`Object#toString`toastring
String(toString)
//Escapeanyspecialregexpcharacters
.replace(/[.*+?^${}()|[\]\/\\]/g,'\\$&')
//Replacementionsof`toString`with`.*?`tokeepthetemplategeneric.
//Replacethinglike`for...`tosupportenvironmentslikeRhinowhichaddextrainfo
//suchasmethodarity.
.replace(/toString|(function).*?(?=\\\()|for.+?(?=\\\])/g,'$1.*?')+'$'
);
functionisNative(value){
vartype=typeofvalue;
returntype=='function'
//Use`Function#toString`tobypassthevalue'sown`toString`method
//andavoidbeingfakedout.
?reNative.test(fnToString.call(value))
//Fallbacktoahostobjectcheckbecausesomeenvironmentswillrepresent
//thingsliketypedarraysasDOMmethodswhichmaynotconformtothe
//normalnativepattern.
:(value&&type=='object'&&reHostCtor.test(toString.call(value)))||false;
}
//exporthoweveryouwant
module.exports=isNative;
}());
//Usage
isNative(alert);//true
isNative(myCustomFunction);//false
这个方法虽然不是那么的简洁,但还是可以完成任务的!
用JavaScript创建新的CSS规则insertRule
有时候我们会使用一个CSS选择器(比如document.querySelectorAll)来获取一个NodeList,然后给它们每个依次修改样式。其实这并不是一种高效的做法,高效的做法是用JavaScript新建一段CSS样式规则:
//BuildabetterSheetobject
Sheet=(function(){
//Buildstyle
varstyle=document.createElement('style');
style.setAttribute('media','screen');
style.appendChild(document.createTextNode(''));
document.head.appendChild(style);
//Buildandreturnasinglefunction
returnfunction(rule){style.sheet.insertRule(rule,style.sheet.cssRules.length);};
})();
//Thencallasafunction
Sheet(".stats{position:relative;top:0px}");
这些做法的效率非常高,在一些场景中,比如使用ajax新加载一段html时,使用上面这个方法,你不需要操作新加载的html内容。
判断网页元素是否具有某种属性和样式matchesSelector
functionmatchesSelector(el,selector){
varp=Element.prototype;
varf=p.matches||p.webkitMatchesSelector||p.mozMatchesSelector||p.msMatchesSelector||function(s){
return[].indexOf.call(document.querySelectorAll(s),this)!==-1;
};
returnf.call(el,selector);
}
//Usage
matchesSelector(document.getElementById('myDiv'),'div.someSelector[some-attribute=true]')
就是这7个JavaScript函数,每个Web程序员都应该知道怎么用它们。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。