This article by Bole Online-Liu Jianchu-j.c translation, into the forest School draft. without permission, no reprint!
English Source: Davidwalsh.name. Welcome to join the translation team.
I remember the early JavaScript that almost never made it easy to do anything, because the browser provider implemented the functionality differently, and not just the edge functionality, but also the basic functionality, such as addEventListener
and attachEvent
. Although the times have changed, there are still some functions that every developer should master in order to accomplish certain functions and improve performance.
debounce
For high energy consumption events, the Debounce function is a good solution. If you do scroll
not resize
use the key*
debounce function for,, and events, then you are almost equal to making a mistake. The following debounce
functions will keep your code efficient:
//returns a function that, if it is called uninterrupted, will not be executed. The function is called again after it has stopped calling N milliseconds to be executed. If there is a pass ' immediate ' argument, the function is immediately scheduled to the execution queue without delay. functionDebounce (func, wait, immediate) {vartimeout; return function() { varContext = This, args =arguments; varlater =function() {timeout=NULL; if(!immediate) func.apply (context, args); }; varCallnow = Immediate &&!timeout; Cleartimeout (timeout); Timeout=SetTimeout (later, wait); if(Callnow) func.apply (context, args); };}; //usagevarMYEFFICIENTFN = Debounce (function() { //all heavy-duty operation}, 250); Window.addeventlistener (' Resize ', MYEFFICIENTFN);
debounce
The function does not allow the callback function to execute more than once within a specified time. This function is especially important when assigning a callback function to an event that will trigger frequently.
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 a certain time to meet your requirements.
functionPoll (FN, callback, Errback, timeout, interval) {varEndTime = Number (NewDate ()) + (Timeout | | 2000); Interval= Interval | | 100; (functionp () {//If the condition is met, execute! if(FN ()) {callback (); } //if the condition is not met, but does not time out, try again Else if(Number (NewDate ()) <endTime) {setTimeout (P, interval); } //do not match and time consumption is too long, then reject! Else{errback (NewError (' Timed out for ' + fn + ': ' +arguments)); } })();} //usage: Make sure elements are visiblePoll (function() { returndocument.getElementById (' Lightbox '). offsetwidth > 0; }, function() { //Execute, successful callback function }, function() { //error, failed callback function });
Polling has been applied for a long time in the web and will still be used in the future.
once
Sometimes you want a given feature to happen only once, similar to the OnLoad event. The following code provides the functionality you are talking about:
functiononce (FN, context) {varresult; return function() { if(FN) {result= fn.apply (Context | | This, arguments); FN=NULL; } returnresult; };} //usagevarCanonlyfireonce = Once (function() {Console.log (' fired! ');}); Canonlyfireonce (); //"fired!"canonlyfireonce ();//Nada //The specified function is not executed
once
The function ensures that a given function can only be called once, preventing duplicate initialization!
getAbsoluteUrl
Getting an absolute URL from a string variable is not as simple as you might think. For some URL
constructors, if you do not provide the necessary parameters you will have problems (and sometimes you really do not know what parameters to provide). Here's an elegant technique that requires you to pass a string to get an absolute URL.
var Getabsoluteurl = (function Span style= "color: #000000;" > () { var A; return function (URL) { if (!a) A = document.createelement (' A ' ); // http://davidwalsh.name/something
The href
processing and URL handling of a element may seem meaningless, and the return statement returns a reliable absolute URL.
isNative
If you want to know whether a specified function is native, or if it can be overridden by a declaration. Here's an easy-to-use code to give you an answer:
;(function() { //internal ' [[Class] ' for processing incoming parameter value varToString =Object.prototype.toString; //the anti-compilation code used to parse the function varFntostring =Function.prototype.toString; //used to detect the host constructor (Safari > 4; really output a specific array) varRehostctor =/^[object. +? constructor]$/; //A standard native method is used as a template to compile a regular expression. //we choose ' object#tostring ' because it is generally not contaminated. varrenative = RegExp (' ^ ' +//force ' object#tostring ' to stringString (toString)//escapes all specified regular expression characters. Replace (/[.*+?^${} () |[] /]/g, ' $& ')//replace the mentioned ' toString ' with '. * ' to maintain the versatility of the template. //will ' for ... ' To compatibility with environments such as Rhino, because these environments add additional information, such as the number of method parameters. . Replace (/tostring| ( function). *? (? = () | for. +? (?=]) /g, ' $1.*? ') + ' $ ' ); functionisnative (value) {varType =typeofvalue; returnType = = ' function '//use ' function#tostring ' (fntostring) to bypass the ' toString ' method of the value itself, so as not to be deceived by forgery. ?renative.test (Fntostring.call (value))//fallback to the check of the host object, because some environments (browsers) treat things like an array of types (typed arrays) as DOM methods, which might not follow a standard native regular expression. : (value && type = = ' object ' && rehostctor.test (Tostring.call (value))) | |false; } //Export FunctionModule.exports =isnative;} ()); //usageisnative (alert);//trueisnative (mycustomfunction);//false
This function is not perfect, but it can accomplish the task!
insertRule
We all know that you can get a NodeList from the selector (through document.querySelectorAll
) and set the style for each element, but what's a more efficient way to style the selector (for example, you can do it in the style table):
varSheet = (function() { //Create <style> label varstyle = document.createelement (' style ')); //If you need to specify a media type, you can add a media (and/or media query) here //style.setattribute (' media ', ' screen ') //style.setattribute (' media ', ' only screens and (max-width:1024px) ') //WebKit Hack:(Style.appendchild (document.createTextNode (")); //add <style> elements to a pageDocument.head.appendChild (style); returnStyle.sheet;}) (); //usageSheet.insertrule ("header {float:left; opacity:0.8; } ", 1);
This is especially useful for a dynamic and heavily dependent AJAX-based Web site. If you set a style for a selector, you don't need to set the style (now or in the future) for each element that matches.
matchesSelector
We often make input checks before proceeding to the next step to ensure a reliable value, or to ensure that the form data is valid, and so on. But how do we usually ensure that an element is qualified for further operation? If an element has a given matching selector, then you can use the matchesSelector
function to verify:
function matchesselector (el, selector) { var p = element.prototype; var function (s) { returnthis)!==-1; }; return // usage matchesselector (document.getElementById (' mydiv '), ' div.someselector[ Some-attribute=true] ')
That's it, the 7 JavaScript functions above should always be remembered by every developer. what function did I miss? Please share it!
7 Basic JS function "translate"