JavaScript's most basic function rollup

Source: Internet
Author: User
Tags regular expression

This article mainly gives you a summary of the most basic JavaScript 7 functions, very practical, the need for small partners can refer to.

I remember early JavaScript, and it's almost impossible to do anything to get around some simple functions, because the browser provider has different functionality, and not just edge functionality, but also basic functionality such as AddEventListener and attachevent. Although times have changed, there are still functions that every developer should be able to master in order to perform certain functions and improve performance.

Debounce

For high energy consumption events, the Debounce function is a good solution. If you do not use the Debounce function for scroll, resize, and key* events, you are almost equal to making a mistake. The following debounce function allows you to keep your code efficient:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21-22 Returns a function that will not be executed if it is invoked without interruption. The function calls it again after it stops calling N milliseconds before it is executed. If there is a pass ' immediate ' parameter, the function is immediately scheduled into the execution queue without delay. function Debounce (func, wait, immediate) {var timeout; return function () {var context = this, args = arguments; var late R = 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 heavy Operations}, 250); Window.addeventlistener (' resize ', MYEFFICIENTFN);

The Debounce function does not allow callback functions to execute more than once in a specified time. This function is particularly important when assigning a callback function for an event that is frequently triggered.

Poll

Although I mentioned the Debounce function above, but if the event does not exist, you can not insert an event to determine the desired state, then you need to check the status at intervals to meet your requirements.

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The 23 24 25 26 27 28 29 30 31 32 33 34 35 36 Function Poll (FN, callback, Errback, timeout, interval) {var endtime = number (new Date ()) + (Timeout | |); interval = Interval | |   100; (function P () {//If the condition is met, execute!)   if (FN ()) {callback ();}   If the condition is not satisfied, but does not time out, again else if (number (new Date ()) < Endtime) {settimeout (P, interval);} does not match and the time consumes too long, reject! else {errback (new Error (' Timed out for ' + fn + ': ' + arguments) ');}) (); }//Usage: Make sure the element is visible poll (function () {return document.getElementById (' Lightbox '). offsetwidth > 0;}, function () {//Execute , successful callback function}, function () {//error, failed callback function});

Polling has been applied to 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 call a feature:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23-24 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 (); Nada//No specified function executed

The once function ensures that a given function can only be invoked once, thereby preventing duplicate initialization!

Getabsoluteurl

Getting an absolute URL from a string variable is not as simple as you might think. For some URL constructors, it can be problematic if you don't provide the necessary parameters (and sometimes you don't really know what parameters to provide). Here's an elegant technique that requires you to pass a string to get the absolute URL.

?

1 2 3 4 5 6 7 8 9 10 11 12 13-14 var Getabsoluteurl = (function () {var A;   return function (URL) {if (!a) a = document.createelement (' a '); a.href = URL; return a.href; };   })(); Usage getabsoluteurl ('/something '); Http://davidwalsh.name/something

The href processing of a element and URL processing seem meaningless, and the return statement returns a reliable absolute URL.

Isnative

If you want to know if a specified function is native, or if you can overwrite it with a declaration. Here's an easy to use code that gives you an answer:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The ;(function () {   //Internal ' [[Class]] ' for processing incoming parameter value ' [[classes]] ' var toString = Object.prototype.toString    / /anti-compilation code for analytic functions var fntostring = Function.prototype.toString;    //to detect the Host builder (Safari > 4; True output-specific array) var rehostctor =/^[object. +? constructor]$/;    //using a standard native method as a template, compile a regular expression.  //We choose ' object#tostring ' because it is generally not contaminated. var renative = RegExp (' ^ ' +  ///convert ' object#tostring ' to String (toString)  //Escape all specified regular expression characters. Replace (/[.*+ ?^${}()| []/]/g, ' $& ')  //Replace the mentioned ' toString ' with '. * ' to maintain the versatility of the template.  //Will ' for ... ' And so on, in order to be compatible with environments such as Rhino, because these environments add additional information, such as the number of method arguments. Replace (/tostring| ( function). *? (? = () | for. +? (?=]) /g, ' $1.*? ' + '$' );   function Isnative (value) {var type = typeof value; return type = = ' function '  //' function#tostring ' (fntostring) bypasses the ' toString ' method of value (value) to avoid being deceived by forgery. Renative.test (Fntostring.call (value))  //fallback to the check of the host object, because some environments (browsers) use things like the array of types (typed arrays) as DOM methods, The standard native regular expression may not be followed at this time. : (value && type = = ' object ' && rehostctor.test (Tostring.call (value)) | | False }    //export function module.exports = isnative; }());  /Usage isnative (alert); True Isnative (mycustomfunction); False

This function is not perfect, but it can complete the task!

Insertrule

We all know that we can get a nodelist by selector (through Document.queryselectorall), and we can set a style for each element, but what's a more efficient way to set the style for the selector (for example, you can do it in the stylesheet):

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24-25 var sheet = (function () {//Create <style> tag var style = document.createelement (' style '); If you need to specify the media type, you can add a media (and/or media query)//Style.setattribute (' media ', ' screen ')//Style.setattribute     ', ' 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);

This is especially useful for a Web site that is dynamic and heavily dependent on AJAX. If you set a style for a selector, you do not need to set a style for each matching element (now or in the future).

Matchesselector

We often make input checksums before we do the next step to make sure that it is a reliable value, or that the form data is valid, and so on. But how do we usually make sure that an element is qualified for further operation? If an element has a given matching selector, you can use the Matchesselector function to verify that:

?

1 2 3 4 5 6 7 8 9 10 function Matchesselector (el, selector) {var p = Element.prototype; var f = p.matches | | p.webkitmatchesselector | | p.mozm Atchesselector | | 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] ')

That's all, the 7 JavaScript functions that every developer should remember at all times. what function did I miss? Please share it!

The above mentioned is the entire content of this article, I hope you can enjoy.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.