/**
* Creates a cache for DOM elements to avoid repeated DOM lookups.
*
* @returns {object} An object with a `get` method to retrieve cached elements.
*/
const domCache = (() => {
const cache = {};
/**
* Retrieves a cached DOM element. If the element is not in the cache,
* it's created, cached, and then returned.
*
* @param {string | Element | Function} selector - The selector to identify the element.
* Can be a string (e.g., 'div#myDiv'),
* an existing Element, or a function that returns an Element.
* @returns {Element} The cached DOM element.
*/
function get(selector) {
if (typeof selector === 'function') {
return selector();
}
if (cache[selector]) {
return cache[selector];
}
let element;
if (typeof selector === 'string') {
element = document.querySelector(selector);
if (!element) {
console.warn(`Element not found for selector: ${selector}`);
cache[selector] = null; // Store null if element is not found.
return null;
}
} else {
element = selector;
}
cache[selector] = element;
return element;
}
return { get };
})();
Add your comment