I remember that in the early JavaScript, there was almost no way to avoid simple functions to accomplish anything, because browser providers implemented differently, and not just edge functions, but also basic functions, such as addEventListener and attachEvent. Although times have changed, there are still some functions that every developer should master in order to facilitate the completion of certain functions and improve performance.
debounce
For high energy consumption events, the debounce function is a good solution. If you don't use the debounce function for scroll, resize, and key* events, then you're almost like making a mistake. The following debounce function can keep your code efficient:
// Returns a function that will not be executed if it is called continuously. The function will be executed after stopping calling N milliseconds. If the 'immediate' parameter is passed, the function will be arranged to the execution queue immediately without delay.function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) (context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) (context, args); }; }; // Usagevar myEfficientFn = debounce(function() { // All heavy operations}, 250); ('resize', myEfficientFn);
The debounce function does not allow callback functions to be executed more than once within a specified time. This function is particularly important when assigning a callback function to an event that is frequently triggered.
poll
Although I mentioned the debounce function above, if the event does not exist, you cannot insert an event to judge the required state, then you need to check whether the state meets your requirements every once in a while.
function poll(fn, callback, errback, timeout, interval) { var endTime = Number(new Date()) + (timeout || 2000); interval = interval || 100; (function p() { // If the condition is satisfied, execute! if(fn()) { callback(); } // If the condition is not met but the timeout has not expired, do it again else if (Number(new Date()) < endTime) { setTimeout(p, interval); } // If it does not match and takes too long, reject it! else { errback(new Error('timed out for ' + fn + ': ' + arguments)); } })(); } // Usage: Make sure the elements are visiblepoll( function() { return ('lightbox').offsetWidth > 0; }, function() { // Execute, successful callback function }, function() { // Error, failed callback function } );
Polling has been used in the web for a long time and will still be used in the future.
once
Sometimes you want a given function to happen only once, similar to the onload event. The following code provides what you mentioned:
function once(fn, context) { var result; return function() { if(fn) { result = (context || this, arguments); fn = null; } return result; }; } // Usagevar canOnlyFireOnce = once(function() { ('Fired!'); }); canOnlyFireOnce(); // "Fired!" canOnlyFireOnce(); // nada // No specified function was executed
The once function ensures that a given function can only be called once, thus preventing repeated initialization!
getAbsoluteUrl
Getting an absolute URL from a string variable is not as simple as you think. For some URL constructors, there will be problems if you don't provide the necessary parameters (and sometimes you really don't know what parameters are provided). Here is an elegant trick, you only need to pass a string to get the corresponding absolute URL.
var getAbsoluteUrl = (function() { var a; return function(url) { if(!a) a = ('a'); = url; return ; }; })(); // UsagegetAbsoluteUrl('/something'); // /something
The href and url processing of the a element seem meaningless, while the return statement returns a reliable absolute URL.
isNative
If you want to know if a specified function is native or can it be overridden by declaration. The following easy-to-use code can give you the answer:
;(function() { // Used to handle the incoming parameter value internal `[[Class]]` var toString = ; // Decompiled code for parsing functions var fnToString = ; // Used to detect host constructors (Safari > 4; really output specific arrays) var reHostCtor = /^[object .+?Constructor]$/; // Use a standard native method as a template to compile a regular expression. // We choose 'Object#toString' because it is not contaminated in general. var reNative = RegExp('^' + // Forced to String String(toString) // Escape all specified regular expression characters .replace(/[.*+?^${}()|[]/]/g, '$&') // Replace the mentioned 'toString' with '.*?' to maintain the template's universality. // Replace characters like 'for ...' to be compatible with environments such as Rhino, because these environments add additional information, such as the number of method parameters. .replace(/toString|(function).*?(?=()| for .+?(?=])/g, '$1.*?') + '$' ); function isNative(value) { var type = typeof value; return type == 'function' // Use 'Function#toString' (fnToString) bypasses the 'toString' method of the value itself to avoid being deceived by forgery. ? ((value)) // Fall back to the check of the host object, because some environments (browsers) treat things like typed arrays as DOM methods, which may not follow standard native regular expressions at this time. : (value && type == 'object' && ((value))) || false; } // Export function = isNative; }()); // UsageisNative(alert); // true isNative(myCustomFunction); // false
Although this function is not perfect, it can complete the task!
insertRule
We all know that we can get a NodeList through the selector (via ) and style each element, but what is more efficient way to style the selector (for example you can do it in the style sheet):
var sheet = (function() { // Create <style> tag var style = ('style'); // If you need to specify a media type, you can add a media (and/or media query) // ('media', 'screen') // ('media', 'only screen and (max-width : 1024px)') // WebKit hack :( (('')); // Add the <style> element to the page (style); return ; })(); // Usage("header { float: left; opacity: 0.8; }", 1);
This is especially useful for a dynamic and heavily dependent website. If you style a selector, you don't need to style each matched element (now or in the future).
matchesSelector
We often perform input verification before performing the next operation to ensure it is a reliable value, or to ensure the form data is valid, etc. But how do we usually ensure that an element is qualified for further operation? If an element has a selector for a given match, you can use the matchesSelector function to verify:
function matchesSelector(el, selector) { var p = ; var f = || || || || function(s) { return [].((s), this) !== -1; }; return (el, selector); } // UsagematchesSelector(('myDiv'), '[some-attribute=true]')
That's it, the above 7 JavaScript functions are something that every developer should always remember. Which function I missed? Please share it!
The above is the entire content of this article, I hope you like it.