[Javascript] Using IIFE to improve code performance

Zhentiw發表於2024-12-03

Example 1

Before

function addEvent(ele, eventName, handler) {
	if (ele.addEventListener) {
		ele.addEventListener(eventName, handler);
	} else if (ele.attachEvent) {
		ele.attachEvent('on' + eventName, handler);
	} else {
		ele['on' + eventName] = handler;
	}
}

After

var addEvent = (function () {
	if (ele.addEventListener) {
		return function (ele, eventName, handler) {
			ele.addEventListener(eventName, handler);
		};
	} else if (ele.attachEvent) {
		return function (ele, eventName, handler) {
			ele.attachEvent('on' + eventName, handler);
		};
	} else {
		return function (ele, eventName, handler) {
			ele['on' + eventName] = handler;
		};
	}
})();

Example 2

Before

function request(options) {
	if (typeof window !== 'undefined') {
		// Browser-side AJAX
	} else {
		// Node.js HTTP
	}
}

After

var request = (function () {
	if (typeof window !== 'undefined') {
		return function (options) {
			// Browser-side AJAX
		};
	} else {
		return function (options) {
			// Node.js HTTP
		};
	}
})();

Example 3

Before

function removeSpace(str) {
	// Test Regex...
	return str.replace(/\s/g, '');
}

After

var removeSpace = (function () {
	var reg = /\s/g;
	return function (str) {
		return str.replace(reg, '');
	};
})();

You don't need to create a regobject everytime when running the function.

相關文章