I remember a few years ago, as long as we were writing JavaScript, we had to use a few common functions, such as, addEventListener
and attachEvent
, not for the very advanced technology and functionality, but some basic tasks, because of the differences between the various browsers caused. Time has passed so long, technology is constantly progressing, there are still some JavaScript functions that are essential for almost all web programmers, or for performance, or for functionality.
debounce
functions to prevent high-frequency calls
This debounce
function is essential for performing event-driven tasks to improve performance. If you are using, and so on, and scroll
resize
so on when the key*
event triggers the execution of the task without using the frequency reduction function, you have made a major mistake. The following frequency reduction function debounce
can make your code more efficient:
Returns a function, which, as long as it continues to be invoked, would not//be triggered. The function would 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;i F (!immediate) func.apply (context, args);}; var callnow = immediate &&!timeout;cleartimeout (timeout); timeout = SetTimeout (later, wait); if (Callnow) Func.apply (context, args);};};/ /Usagevar MYEFFICIENTFN = debounce (function () {//All of the taxing stuff do}, Window.addeventlistener (' Resize ', my EFFICIENTFN);
This debounce
function reduces the frequency of its execution by allowing only the callback function that you provide at a given time interval to execute once. Such restrictions are especially important when encountering high-frequency triggering events.
set time/frequency cycle detection function
The function mentioned above debounce
is triggered by an event. But sometimes no such event is available, so we can only write a function on our own to check it every other time.
Function Poll (FN, callback, err, timeout, interval) { var startTime = (new Date ()). GetTime (); var pi = window.setinterval (function () { if (Math.floor ((new Date). GetTime ()-startTime)/+) <= timeout) {
if (FN ()) { callback (); } } else { window.clearinterval (pi); Err (); } }, Interval)}
disable repeated calls and allow only one
once
function to execute once
Most of the time, we just want an action to be performed only once, as if we were using it onload
to only execute once the load is complete. The following function will allow you to execute the operation once and then not repeat it.
Function once (FN, context) {var result;return function () {if (fn) {result = Fn.apply (Context | | this, arguments); fn = nul l;} return result;};} Usagevar canonlyfireonce = once (function () {console.log (' fired! ');}); Canonlyfireonce (); "Fired!" Canonlyfireonce (); Nada
This once
function ensures that the function you provide is executed only once, preventing repetition.
get the absolute address
getAbsoluteUrl
of a link
Getting the absolute address of the link is not as simple as you might think. Here is a very useful function that can obtain an absolute address based on the relative address you enter:
var Getabsoluteurl = (function () {var a;return function (URL) {if (!a) a = document.createelement (' a '); a.href = Url;return A . href;};}) ();//Usagegetabsoluteurl ('/something '); Http://www.webhek.com/something
The a
label is used here href
to generate the complete absolute URL, which is very reliable.
determine if a JavaScript function is a system-
isNative
native function
Many third-party JS scripts introduce new functions into global variables, some even overwrite the native functions of the system, and the following method is to check if they are native functions:
;(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 the 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 is ing faked out. ? Renative.test (Fntostring.call (value))//Fallback to a host object check because some environments would represent Things like typed arrays as DOM methods which could 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
Although this method is not so concise, but still can complete the task!
Create a new CSS
insertRule
rule with JavaScript
Sometimes we use a CSS selector (for example document.querySelectorAll
) to get a NodeList, and then we give each of them a style in turn. In fact, this is not an efficient approach, and it is efficient to create a new CSS style rule with javascript:
Build a better Sheet object Sheet = (function () {//Build Stylevar style = document.createelement (' style '); Style.setatt Ribute (' media ', ' screen '); Style.appendchild (document.createTextNode ("));d Ocument.head.appendChild (style);// Build and return a single functionreturn function (rule) {style.sheet.insertRule (rule, style.sheet.cssRules.length);};} ) ();/Then call as a Functionsheet (". stats {position:relative; top:0px} ");
These practices are very efficient, and in some scenarios, such as using AJAX to load a new piece of HTML, you do not need to manipulate the newly loaded HTML content.
determine if a page element has a property and style
matchesSelector
function Matchesselector (el, selector) {var p = element.prototype;var f = p.matches | | p.webkitmatchesselector | | p.mozmat Chesselector | | P.msmatchesselector | | function (s) {return [].indexof.call (Document.queryselectorall (s), this)!==-1;}; Return F.call (el, selector);} Usagematchesselector (document.getElementById (' mydiv '), ' div.someselector[some-attribute=true] ')
This is the 7 JavaScript functions, and each Web programmer should know how to use them. You can write other functions that you think are necessary in the comments and share them, thank you.
Original link: http://www.webhek.com/7-essential-javascript-functions
[7 JavaScript functions required for developer]web