You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Returns a function, that, as long as it continues to be invoked, will not// be triggered. The function will be called after it stops being called for// N milliseconds. If `immediate` is passed, trigger the function on the// leading edge, instead of the trailing.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);};};// UsagevarmyEfficientFn=debounce(function(){// All the taxing stuff you do},250);window.addEventListener('resize',myEfficientFn);
functionpoll(fn,callback,errback,timeout,interval){varendTime=Number(newDate())+(timeout||2000);interval=interval||100;(functionp(){// If the condition is met, we're done! if(fn()){callback();}// If the condition isn't met but the timeout hasn't elapsed, go againelseif(Number(newDate())<endTime){setTimeout(p,interval);}// Didn't match and too much time, reject!else{errback(newError('timed out for '+fn+': '+arguments));}})();}// Usage: ensure element is visiblepoll(function(){returndocument.getElementById('lightbox').offsetWidth>0;},function(){// Done, success callback},function(){// Error, failure callback});
;(function(){// Used to resolve the internal `[[Class]]` of valuesvartoString=Object.prototype.toString;// Used to resolve the decompiled source of functionsvarfnToString=Function.prototype.toString;// Used to detect host constructors (Safari > 4; really typed array specific)varreHostCtor=/^\[object .+?Constructor\]$/;// Compile a regexp using a common native method as a template.// We chose `Object#toString` because there's a good chance it is not being mucked with.varreNative=RegExp('^'+// Coerce `Object#toString` to a stringString(toString)// Escape any special regexp characters.replace(/[.*+?^${}()|[\]\/\\]/g,'\\$&')// Replace mentions of `toString` with `.*?` to keep the template generic.// Replace thing like `for ...` to support environments like Rhino which add extra info// such as method arity..replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,'$1.*?')+'$');functionisNative(value){vartype=typeofvalue;returntype=='function'// Use `Function#toString` to bypass the value's own `toString` method// and avoid being faked out.
? reNative.test(fnToString.call(value))// Fallback to a host object check because some environments will represent// things like typed arrays as DOM methods which may not conform to the// normal native pattern.
: (value&&type=='object'&&reHostCtor.test(toString.call(value)))||false;}// export however you wantmodule.exports=isNative;}());// UsageisNative(alert);// trueisNative(myCustomFunction);// false
varsheet=(function(){// Create the <style> tagvarstyle=document.createElement('style');// Add a media (and/or media query) here if you'd like!// style.setAttribute('media', 'screen')// style.setAttribute('media', 'only screen and (max-width : 1024px)')// WebKit hack :(style.appendChild(document.createTextNode(''));// Add the <style> element to the pagedocument.head.appendChild(style);returnstyle.sheet;})();// Usagesheet.insertRule("header { float: left; opacity: 0.8; }",1);
7 个必不可少的 JavaScript 函数
原文地址:http://davidwalsh.name/essential-javascript-functions
我记得,早期的 JavaScript ,一个简单的功能,需要知道关于它的一切,因为不同的的浏览器厂商对特性(feature)的实现是不同的,不仅是边缘特性(feature),一些基本特性(feature)也是如此,比如
addEventListener
和attachEvent
。随着时间的改变,仍然有些函数是每个开发者必须放在他们的武器库里,因为它们具有更好的性能和功能。debounce
Debounce 函数被称为变革者,当它带来性能提升时候。如果你不和
scroll
,resize
,key*
等事件一起使用 debounce 函数,那你可能做错了。这里的 debounce 函数会保持你代码的效率:Debounce 函数在每个给定的时间里不允许回调函数被调用超过一次。这是特别重要的,当你给频繁发生的事件注册一个回调函数时。
Poll
正如我提到的 debounce 函数(译者注:前面这句不明白)。有时,你不能接收表示期望状态的结果 -- 如果这个结果不存在,你需要在一段时间内检查你的期望状态:
Polling 早已在 web 上使用,并将在未来继续发光发热!
once
有些时候,你希望给定的函数仅执行一次,类似你使用 onload 事件的方式,下面的代码提供了你所说的功能:
Once 函数确保一个给定的函数仅被调用一次,因而,可以防止重复初始化!
getAbsoluteUrl
从一个字符串变量得到一个绝对路径的 URL 并不像你想的那么容易。有个 URl 构造函数但是如果你不能提供必要的参数的话(有时候,你确实不能提供参数),它不能正常工作。这里有一个取得绝对路径的奇淫巧计。
isNative
如果你想覆盖一个给定的函数,需要知道它是否原生的,下面的代码可以给你答案:
这个函数不是很漂亮,但是它能够完成任务!
insertRule
我们都知道我们可以通过一个选择器抓取 NodeList (通过
document.querySelectorAll
) 并为它们添加样式,但是更高效的方式是对选择器直接设置样式:这个函数特别有用,当你工作在一个动态的,重度使用AJAX的网站时。如果你对一个选择器直接设置样式,你就不必为每个匹配该选择器的元素设置样式。
matchesSelector
通常情况下,在进行下一步之前,我们需要验证输入;确保是一个真值,确保表单数据有效。但是我们是否经常确定一个元素合格再进行下一步?你可以使用 matchesSelector 方法去校验一个元素是否与给定的选择器匹配:
每个开发者都应该将这7个JavaScript函数放入他们的工具箱中。如果我漏掉一个函数?请分享它!
The text was updated successfully, but these errors were encountered: