A few years ago, as long as we write JavaScript, we had to use several commonly used functions, such as addEventListener and attachEvent, which were not for advanced technologies and functions, but for some basic tasks, because of the differences between various browsers. As time passes, technology is constantly improving, there are still some JavaScript functions that are essential for almost all web programmers, either for performance or for functionality.
Debounce function that prevents high-frequency calls
This debounce function is an essential performance-enhancing function for those performing event-driven tasks. If you do not use the downscaling function when using scroll, resize, key* and other events to trigger tasks, you will make a major mistake. The following down-frequency debounce function debounce can make your code efficient:
// Return 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) (context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) (context, args); }; }; // Usage var myEfficientFn = debounce(function() { // All the taxing stuff you do }, 250); ('resize', myEfficientFn);
The debounce function only allows the callback function you provide to execute once within a given time interval, thereby reducing its execution frequency. Such restrictions are particularly important when high-frequency triggered events are encountered.
Set time/frequency cycle detection function
The debounce function mentioned above is triggered by the help of an event. But sometimes there is no such event available, so we can only write a function ourselves to check it every once in a while.
function poll (fn, callback, err, timeout, interval) { var startTime = (new Date()).getTime(); var pi = (function(){ if ((((new Date).getTime() - startTime) / 1000) <= timeout) { if (fn()) { callback(); } } else { (pi); err(); } }, interval) }
Once function that prohibits repeated calls and only allows execution once
Many times, we only want some action to be executed once, just like we use onload to limit it to be executed only once when the load is completed. The following function will allow your operation to be executed once and will not be executed repeatedly.
function once(fn, context) { var result; return function() { if(fn) { result = (context || this, arguments); fn = null; } return result; }; } // Usage var canOnlyFireOnce = once(function() { ('Fired!'); }); canOnlyFireOnce(); // "Fired!" canOnlyFireOnce(); // nada
This once function can ensure that the function you provide is executed only once and prevent repeated execution.
Get the absolute address of a link getAbsoluteUrl
Getting the absolute address of the link is not as simple as you think. The following is a very practical function that can obtain the absolute address based on the relative address you entered:
var getAbsoluteUrl = (function() { var a; return function(url) { if(!a) a = ('a'); = url; return ; }; })(); // Usage getAbsoluteUrl('/something');
Here we use the a tag href to generate a complete absolute URL, which is very reliable.
Determine whether a JavaScript function is a system native function isNative
Many third-party js scripts will introduce new functions into global variables, and some will even overwrite the system's native functions. The following method is to check whether it is a native function:
;(function() { // Used to resolve the internal `[[Class]]` of values var toString = ; // Used to resolve the decompiled source of functions var fnToString = ; // 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. ? ((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' && ((value))) || false; } // export however you want = isNative; }()); // Usage isNative(alert); // true isNative(myCustomFunction); // false
Although this method is not so concise, it can still complete the task!
Create new CSS rules with JavaScript insertRule
Sometimes we use a CSS selector (such as ) to get a NodeList and then modify the styles to each of them in turn. In fact, this is not an efficient approach. It is an efficient approach to create a new CSS style rule using JavaScript:
// Build a better Sheet object Sheet = (function() { // Build style var style = ('style'); ('media', 'screen'); (('')); (style); // Build and return a single function return function(rule){ ( rule, ); } ; })(); // Then call as a function Sheet(".stats { position: relative ; top: 0px }") ;
These practices are very efficient. In some scenarios, such as when using ajax to load a new html, you do not need to operate the newly loaded html content.
Determine whether web page elements have certain attributes and styles matchesSelector
function matchesSelector(el, selector) { var p = ; var f = || || || || function(s) { return [].((s), this) !== -1; }; return (el, selector); } // Usage matchesSelector(('myDiv'), '[some-attribute=true]')
These 7 JavaScript functions are all that every web programmer should know how to use them.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.