Web开发必备:7个实用的JavaScript工具函数

作者:缓存笔记时间:2026-10-30 09:06:16浏览:583

本文介绍了Web开发中七个不可或缺的JavaScript工具函数。通过debounce实现高频事件降频,利用poll进行定时轮询,使用once确保动作仅执行一次,以及getAbsoluteUrl处理URL转换。此外还包括isNative检测原生函数、insertRule动态添加CSS规则以及matchesSelector匹配选择器,旨在帮助开发者提升代码效率与性能。

引言

在早期的Web开发中,由于浏览器之间的差异,开发者必须使用一些通用函数来处理基本任务,例如addEventListener和attachEvent。尽管技术不断进步,但至今仍有一些JavaScript函数是Web开发者必备的工具,它们要么为了提升性能,要么为了增强功能。

防高频调用的debounce函数

防高频调用的debounce函数

debounce函数对于处理事件驱动的任务至关重要,它是提升性能的关键。如果在scroll、resize或键盘事件(key*)触发任务时不使用降频函数,可能会导致严重的性能问题。下面的debounce函数能让代码运行更加高效:


// 返回一个函数,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) 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 the taxing stuff you do
}, 250);
window.addEventListener('resize', myEfficientFn);

该debounce函数确保在指定的时间间隔内,提供的回调函数只执行一次,从而降低其执行频率。在处理高频触发的事件时,这种限制显得尤为重要。

设定时间/频率循环检测函数

设定时间/频率循环检测函数

上述debounce函数依赖于特定事件的触发。然而,在某些场景下并没有现成的事件可用,这时我们需要编写一个函数,每隔一段时间执行一次检查。


function poll (fn, callback, err, timeout, interval) {
 var startTime = (new Date()).getTime();
 var pi = window.setInterval(function(){
  if (Math.floor(((new Date).getTime() - startTime) / 1000) <= timeout) {
   if (fn()) {
    callback();
   }
  } else {
   window.clearInterval(pi);
   err();
  }
 }, interval)
}

禁止重复调用、只允许执行一次的once函数

禁止重复调用、只允许执行一次的once函数

很多时候,我们希望某个动作只执行一次,就像使用onload来限定仅在加载完成时执行一次。下面的函数可以确保操作在首次执行后不再重复:


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

once函数保证提供的函数只执行唯一的一次,防止重复执行。

获取链接的绝对地址getAbsoluteUrl

获取链接的绝对地址getAbsoluteUrl

获取链接的绝对地址并不像想象中那么简单。下面是一个实用的函数,可以根据输入的相对地址获取绝对地址:


var getAbsoluteUrl = (function() {
 var a;

 return function(url) {
 if(!a) a = document.createElement('a');
 a.href = url;

 return a.href;
 };
})();

// Usage
getAbsoluteUrl('/something'); 

这里利用了a标签的href属性来生成完整的绝对URL,这种方法非常可靠。

判断JavaScript函数是否是系统原生函数isNative

判断JavaScript函数是否是系统原生函数isNative

许多第三方JavaScript脚本会在全局变量中引入新函数,有些甚至会覆盖系统原生函数。下面的方法用于检查一个函数是否为原生函数:


;(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 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.
  ? reNative.test(fnToString.call(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' && reHostCtor.test(toString.call(value))) || false;
 }
 
 // export however you want
 module.exports = isNative;
}());

// Usage
isNative(alert); // true
isNative(myCustomFunction); // false

虽然这个方法不够简洁,但它能够完成任务。

用JavaScript创建新的CSS规则insertRule

用JavaScript创建新的CSS规则insertRule

有时我们会使用CSS选择器(如document.querySelectorAll)获取NodeList,然后逐个修改样式。这并非高效的做法,更高效的方式是用JavaScript新建一段CSS样式规则:


// Build a better Sheet object 
Sheet = (function() {
 // Build style
 var style = document.createElement('style');
 style.setAttribute('media', 'screen');
 style.appendChild(document.createTextNode(''));
 document.head.appendChild(style);

 // Build and return a single function
 return function(rule){ style.sheet.insertRule( rule, style.sheet.cssRules.length ); } ;
})();

// Then call as a function
Sheet(".stats { position: relative ; top: 0px }") ;

这种做法效率非常高。在某些场景中,例如使用ajax新加载一段html时,使用上述方法,你无需操作新加载的html内容。

判断网页元素是否具有某种属性和样式matchesSelector

判断网页元素是否具有某种属性和样式matchesSelector


function matchesSelector(el, selector) {
 var p = Element.prototype;
 var f = p.matches || p.webkitMatchesSelector || p.mozMatchesSelector || 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]')

总结

以上就是这7个JavaScript函数,每个Web程序员都应该知道如何使用它们。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

作者最新文章