« Back to Index

Create Elements using memoization technique (modified to @GarrettS’ points)

View original Gist on GitHub

Tags: #js

createElement.js

/**
 * The following method creates a new element or returns a copy of an element already created by this script.
 *
 * @param tagname { String } element to be created/copied
 * @return { Element/Node } the newly created element
 */
createElement: (function(){
	// Memorize previous elements created
	var cache = {};
	
	return function(tagname) {
		if (!(tagname in cache)) {
			// Create new instance of specified element and store it
			cache[tagname] = document.createElement(tagname);
		}
		
		// If we've already created an element of the specified kind then duplicate it
		return cache[tagname].cloneNode(false);
	}
}())