我记得在JavaScript的早期,您需要一个几乎所有功能的简单功能,因为浏览器供应商实现的功能有所不同,而不仅仅是边缘功能,基本功能(例如addEventListener和attachEvent 。 时代已经变了,但是每个开发人员仍然需要在其功能库中拥有一些功能,以实现易于使用的性能。
在事件推动的表演中,防反弹功能可以改变游戏规则。 如果您不使用带有scroll , resize , key*事件的反跳功能,则可能是错误的。 这是一个debounce功能,可保持代码高效:
// 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. function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; // Usage var myEfficientFn = debounce(function() { // All the taxing stuff you do }, 250); window.addEventListener('resize', myEfficientFn);debounce功能不允许在每个给定的时间范围内多次使用回调。 将回调函数分配给频繁触发的事件时,这一点尤其重要。
正如我在debounce函数中提到的那样,有时您不必插入事件来表示所需的状态-如果该事件不存在,则需要定期检查所需的状态:
// The polling function function poll(fn, timeout, interval) { var endTime = Number(new Date()) + (timeout || 2000); interval = interval || 100; var checkCondition = function(resolve, reject) { // If the condition is met, we're done! var result = fn(); if(result) { resolve(result); } // If the condition isn't met but the timeout hasn't elapsed, go again else if (Number(new Date()) < endTime) { setTimeout(checkCondition, interval, resolve, reject); } // Didn't match and too much time, reject! else { reject(new Error('timed out for ' + fn + ': ' + arguments)); } }; return new Promise(checkCondition); } // Usage: ensure element is visible poll(function() { return document.getElementById('lightbox').offsetWidth > 0; }, 2000, 150).then(function() { // Polling done, now do something else! }).catch(function() { // Polling timed out, handle the error! });长期以来,轮询在网络上一直很有用,并且在将来仍将继续!
有时,您希望给定功能仅发生一次,类似于您使用onload事件的方式。 这段代码为您提供了所说的功能:
function once(fn, context) { var result; return function() { if(fn) { result = fn.apply(context || this, arguments); fn = null; } return result; }; } // Usage var canOnlyFireOnce = once(function() { console.log('Fired!'); }); canOnlyFireOnce(); // "Fired!" canOnlyFireOnce(); // nadaonce函数确保给定的函数只能被调用一次,从而防止重复初始化!
从变量字符串获取绝对URL并不像您想的那么容易。 有URL构造函数,但是如果您不提供必需的参数(有时却不能提供),它可以起作用。 这是一个获取URL和输入字符串的绝对技巧:
var getAbsoluteUrl = (function() { var a; return function(url) { if(!a) a = document.createElement('a'); a.href = url; return a.href; }; })(); // Usage getAbsoluteUrl('/something'); // https://davidwalsh.name/something“ burn”元素href为您处理和URL废话,从而提供可靠的绝对URL。
知道给定函数是否是本机函数可以表明您是否愿意重写它。 这个方便的代码可以为您提供答案:
;(function() { // Used to resolve the internal `[[Class]]` of values var toString = Object.prototype.toString; // Used to resolve the decompiled source of functions var fnToString = Function.prototype.toString; // Used to detect host constructors (Safari > 4; really typed array specific) var reHostCtor = /^\[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. var reNative = RegExp('^' + // Coerce `Object#toString` to a string String(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.*?') + '$' ); function isNative(value) { var type = typeof value; return type == '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 want module.exports = isNative; }()); // Usage isNative(alert); // true isNative(myCustomFunction); // false该功能不是很漂亮,但是可以完成工作!
我们都知道我们可以从选择器中获取一个NodeList(通过document.querySelectorAll )并为它们提供样式,但是更有效的方法是将该样式设置为选择器(就像在样式表中一样):
var sheet = (function() { // Create the <style> tag var style = 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 page document.head.appendChild(style); return style.sheet; })(); // Usage sheet.insertRule("header { float: left; opacity: 0.8; }", 1);在动态的AJAX繁重的网站上工作时,这尤其有用。 如果将样式设置为选择器,则无需考虑对可能与该选择器匹配的每个元素进行样式设置(现在或将来)。
通常,我们会在前进之前验证输入; 确保真实值,确保表单数据有效等。但是,我们要确保元素有资格继续前进的频率是多少? 您可以使用matchesSelector函数来验证元素是否与给定的选择器匹配:
function matchesSelector(el, selector) { var p = Element.prototype; var f = p.matches || p.webkitMatchesSelector || p.mozMatchesSelector || p.msMatchesSelector || function(s) { return [].indexOf.call(document.querySelectorAll(s), this) !== -1; }; return f.call(el, selector); } // Usage matchesSelector(document.getElementById('myDiv'), 'div.someSelector[some-attribute=true]')那里有:每个开发人员都应在其工具箱中保留的七个JavaScript函数。 有我错过的功能吗? 请分享!
.x-secondary-small { display: none; } @media only screen and (max-width: 600px) { .x-secondary { max-height: none; } .x-secondary-large { display: none; } .x-secondary-small { display: block; } }翻译自: https://davidwalsh.name/essential-javascript-functions