DIV CSS 佈局教程網

JavaScript 開發者都該掌握的基礎實用函式
編輯:關於JavaScript     

早期寫 JavaScript 時,幾乎做任何事都離不開一些簡單的函式,因為瀏覽器實作差異大,連 addEventListener 與 attachEvent 這類基礎功能都不統一。雖然時代變了,但仍有幾個函式是每個開發者都該熟練掌握的,以便完成某些功能並提升效能。

debounce(防抖)

對於高耗能事件,debounce 是很好的解法。若不對 scroll、resize、key* 等事件做防抖,幾乎等於犯了效能錯誤:

 // 回傳一個函式,若它被連續呼叫則不會執行,直到停止呼叫 N 毫秒後才會執行
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);
 };
};
// 用法
var myEfficientFn = debounce(function() {
 // 所有繁重的操作
}, 250);
window.addEventListener('resize', myEfficientFn);

debounce 能確保回呼函式在指定時間內不會執行超過一次,對頻繁觸發的事件特別重要。

poll(輪詢)

若事件不存在,無法插入事件來判斷狀態,就需要每隔一段時間檢查一次:

 function poll(fn, callback, errback, timeout, interval) {
 var endTime = Number(new Date()) + (timeout || 2000);
 interval = interval || 100;
 (function p() {
 if(fn()) {
 callback();
 } else if (Number(new Date()) < endTime) {
 setTimeout(p, interval);
 } else {
 errback(new Error('timed out for ' + fn + ': ' + arguments));
 }
 })();
}
// 用法:確保元素可見
poll(
 function() { return document.getElementById('lightbox').offsetWidth > 0; },
 function() { /* 成功的回呼函式 */ },
 function() { /* 錯誤的回呼函式 */ }
);

once(只執行一次)

有時希望某功能只發生一次,類似 onload:

 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(); // "Fired!"
canOnlyFireOnce(); // 不再執行

getAbsoluteUrl(取得絕對網址)

 var getAbsoluteUrl = (function() {
 var a;
 return function(url) {
 if(!a) a = document.createElement('a');
 a.href = url;
 return a.href;
 };
})();
// 用法
getAbsoluteUrl('/something'); // https://davidwalsh.name/something 

isNative(判斷是否原生函式)

 ;(function() {
 var toString = Object.prototype.toString;
 var fnToString = Function.prototype.toString;
 var reHostCtor = /^[object .+?Constructor]$/;
 var reNative = RegExp('^' + String(toString).replace(/[.*+?^${}()|[\]/]/g, '$&').replace(/toString|(function).*?(?=()| for .+?(?=\])/g, '$1.*?') + '$');
 function isNative(value) {
 var type = typeof value;
 return type == 'function'
 ? reNative.test(fnToString.call(value))
 : (value && type == 'object' && reHostCtor.test(toString.call(value))) || false;
 }
 module.exports = isNative;
}());
// 用法
isNative(alert); // true
isNative(myCustomFunction); // false

insertRule(動態插入樣式規則)

 var sheet = (function() {
 var style = document.createElement('style');
 style.appendChild(document.createTextNode(''));
 document.head.appendChild(style);
 return style.sheet;
})();
// 用法
sheet.insertRule("header { float: left; opacity: 0.8; }", 1);

對重度依賴 AJAX 的動態網站特別有用:只要為選擇器設定一次樣式,就不必為每個符合的元素逐一設定。

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);
}
// 用法
matchesSelector(document.getElementById('myDiv'), 'div.someSelector[some-attribute=true]') 

以上七個函式——debounce、poll、once、getAbsoluteUrl、isNative、insertRule 與 matchesSelector——都是每個 JavaScript 開發者值得時刻牢記的實用工具。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved