JavaScript most basic function Rollup _javascript tips

Source: Internet
Author: User

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.


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:

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 later = 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
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.


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.

Function Poll (FN, callback, Errback, timeout, interval) {
  var endtime = number (new Date ()) + (Timeout | |);
  Interval = Interval | | ;
  (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.


Sometimes, you want a given function to happen only once, similar to the OnLoad event. The following code provides what you call a feature:

Function once (FN, context) { 
  var result;
  return function () { 
    if (FN) {result
      = fn.apply (Context | | this, arguments);
      fn = null;
    return result;}
var canonlyfireonce = once (function () {
  console.log (' fired! ');
Canonlyfireonce (); 
Canonlyfireonce (); 
//No specified function executed

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


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.

var Getabsoluteurl = (function () {
  var A;
  return function (URL) {
    if (!a) a = document.createelement (' a ');
    a.href = URL;
    return A.href
) ();
getabsoluteurl ('/something '); 

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


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:

;(function () {//Internal ' [[Class]] ' var toString = Object.prototype.toString used to process incoming parameter value;
Anti-compilation Code for analytic functions var fntostring = Function.prototype.toString; Used to detect the host builder (Safari > 4; True output-specific array) var rehostctor =/^[object. +?
Compile a regular expression using a standard native method as a template.
 We choose ' object#tostring ' because it is generally not contaminated. var renative = RegExp (' ^ ' +//Will ' object#tostring ' be forced to string (toString)///Escape all specified regular expression characters. Replace (/[.*+?^$ {}()|
[]/]/g, ' $& ']//Replace the mentioned ' toString ' with '. * ' to maintain the versatility of the template. The ' 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 (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, and the standard native regular expression may not be followed at this point. : (value && type = = ' object ' &&Rehostctor.test ( (value)) | |
}//Export function module.exports = isnative;
Usage isnative (alert); 
True Isnative (mycustomfunction); False

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


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):

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 ') here//
Style.setattribute (' media ', ' only screens and (max-width:1024px) ')
//WebKit Hack:(
  style.appendchild ( document.createTextNode (")");
Add the <style> element to the page
  Document.head.appendChild (style);
  return style.sheet;
}) ();
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).

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 normally ensure 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:

function Matchesselector (el, selector) {
  var p = element.prototype;
  var f = p.matches | | P.webkitmatchesselector | | P.mozmatchesselector | | P.msmatchesselector | | function (s) {return
    [] (Document.queryselectorall (s), this)!==-1;
  Return (el, selector);
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 out!

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: 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.