7 funciones esenciales de JavaScript -

Recuerdo los primeros días de JavaScript, donde se necesitaba una función simple para casi todo porque los proveedores de navegadores implementaban funciones de manera diferente, y no solo funciones de vanguardia, funciones básicas, como addEventListenery attachEvent. Los tiempos han cambiado, pero todavía hay algunas funciones que cada desarrollador debería tener en su arsenal, para lograr un rendimiento con multas de facilidad funcional.

Índice de contenidos
  1. debounce
  2. poll
  3. once
  4. getAbsoluteUrl
  5. isNative
  6. insertRule
  7. matchesSelector

debounce

La función antirrebote puede cambiar las reglas del juego cuando se trata de rendimiento impulsado por eventos. Si no está utilizando una función antirrebote con un scrollevento resize, key*probablemente lo esté haciendo mal. Aquí hay una debouncefunción para mantener su código eficiente:

// Devuelve una función que, mientras se siga invocando, no // se activará. La función se llamará después de que deje de llamarse durante // N milisegundos. Si se pasa `inmediato`, active la función en el // borde anterior, en lugar de la función final debounce(func, wait, inmediata) {var timeout;return function() {var context = this, args = arguments;var más tarde = función() {timeout = null;if (!inmediato) func.apply(context, args);};var callNow = inmediato !timeout;clearTimeout(timeout);timeout = setTimeout(más tarde, espere);if (callNow ) func.apply(context, args);};};// Usagevar myEfficientFn = debounce(function() {// Todas las cosas exigentes que haces}, 250);window.addEventListener('resize', myEfficientFn) ;

La debouncefunción no permitirá que se utilice una devolución de llamada más de una vez por un período de tiempo determinado. Esto es especialmente importante cuando se asigna una función de devolución de llamada a eventos que se activan con frecuencia.

poll

Como mencioné con la debouncefunción, a veces no puedes conectarte a un evento para indicar un estado deseado; si el evento no existe, debes verificar el estado deseado a intervalos:

// La función de sondeofunction poll(fn, timeout, intervalo) { var endTime = Number(new Date()) + (timeout || 2000); intervalo = intervalo || 100; var checkCondition = function(resolve, rechazar) { // Si se cumple la condición, ¡hemos terminado! resultado var = fn(); si(resultado) { resolver(resultado); } // Si no se cumple la condición pero el tiempo de espera no ha transcurrido, vuelva a hacerlo else if (Number(new Date()) endTime) { setTimeout(checkCondition, intervalo, resolve, rechazar); } // No coincidió y demasiado tiempo, ¡rechaza! else { rechazar(nuevo Error('se agotó el tiempo de espera para ' + fn + ': ' + argumentos)); } }; return new Promise(checkCondition);}// Uso: asegúrese de que el elemento sea visiblepoll(function() {return document.getElementById('lightbox').offsetWidth 0;}, 2000, 150).then(function() { // Sondeo ¡Listo, ahora haz otra cosa!}).catch(function() { // Se agotó el tiempo de espera del sondeo, ¡gestiona el error!});

¡Las encuestas han sido útiles en la web durante mucho tiempo y seguirán siéndolo en el futuro!

once

Hay ocasiones en las que prefieres que una determinada funcionalidad solo suceda una vez, de forma similar a como usarías un onloadevento. Este código le proporciona dicha funcionalidad:

function once(fn, contexto) { var resultado;return function() { if(fn) {resultado = fn.apply(context || this, arguments);fn = null;}devolver resultado;};}// Usagevar canOnlyFireOnce = una vez(función() {console.log('¡Despedido!');});canOnlyFireOnce(); // "¡Despedido!"canOnlyFireOnce(); // nada

La oncefunción garantiza que una función determinada solo se pueda llamar una vez, ¡evitando así una inicialización duplicada!

getAbsoluteUrl

Obtener una URL absoluta a partir de una cadena variable no es tan fácil como cree. Está el URLconstructor, pero puede funcionar mal si no proporciona los argumentos requeridos (lo que a veces no es posible). Aquí hay un truco sencillo para obtener una URL absoluta y una entrada de cadena:

var getAbsoluteUrl = (función() {var a;return function(url) {if(!a) a = document.createElement('a');a.href = url;return a.href;};})() ;// UsogetAbsoluteUrl('/algo'); // https://davidwalsh.nombre/algo

El elemento "grabar" hrefmaneja URL sin sentido para usted, proporcionando a cambio una URL absoluta y confiable.

isNative

Saber si una función determinada es nativa o no puede indicar si está dispuesto a anularla. Este práctico código puede darte la respuesta:

;(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;}());// UsageisNative(alert); // trueisNative(myCustomFunction); // false

The function isn’t pretty but it gets the job done!

insertRule

We all know that we can grab a NodeListfrom a selector (via document.querySelectorAll) and give each of them a style, but what’s more efficient is setting that style to a selector (like you do in a stylesheet):

var sheet = (function() {// Create the style tagvar 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 pagedocument.head.appendChild(style);return style.sheet;})();// Usagesheet.insertRule("header { float: left; opacity: 0.8; }", 1);

This is especiallyuseful when working on a dynamic, AJAX-heavy site. If you set the style to a selector, you don’t need to account for styling each element that may match that selector (now or in the future).

matchesSelector

Oftentimes we validate input before moving forward; ensuring a truthy value, ensuring formsdata is valid, etc. But how often do we ensure an element qualifies for moving forward? You can use a matchesSelector function to validate if an element is of a given selector match:

función coincide conSelector(el, selector) {var p = Element.prototype;var f = p.matches || p.webkitMatchesSelector || p.mozMatchesSelector || p.msMatchesSelector || función(es) {return [].indexOf.call(document.querySelectorAll(s), this) !== -1;};return f.call(el, selector);}// UsagematchesSelector(document.getElementById(' myDiv'), 'div.someSelector[algún-atributo=verdadero]')

Ahí lo tienes: siete funciones de JavaScript que todo desarrollador debería tener en su caja de herramientas. ¿Tiene alguna función que me perdí? ¡Por favor, comparte!

Te podría interesar...

Deja una respuesta

Subir