1. /**
  2. * Creates a cache for DOM elements to avoid repeated DOM lookups.
  3. *
  4. * @returns {object} An object with a `get` method to retrieve cached elements.
  5. */
  6. const domCache = (() => {
  7. const cache = {};
  8. /**
  9. * Retrieves a cached DOM element. If the element is not in the cache,
  10. * it's created, cached, and then returned.
  11. *
  12. * @param {string | Element | Function} selector - The selector to identify the element.
  13. * Can be a string (e.g., 'div#myDiv'),
  14. * an existing Element, or a function that returns an Element.
  15. * @returns {Element} The cached DOM element.
  16. */
  17. function get(selector) {
  18. if (typeof selector === 'function') {
  19. return selector();
  20. }
  21. if (cache[selector]) {
  22. return cache[selector];
  23. }
  24. let element;
  25. if (typeof selector === 'string') {
  26. element = document.querySelector(selector);
  27. if (!element) {
  28. console.warn(`Element not found for selector: ${selector}`);
  29. cache[selector] = null; // Store null if element is not found.
  30. return null;
  31. }
  32. } else {
  33. element = selector;
  34. }
  35. cache[selector] = element;
  36. return element;
  37. }
  38. return { get };
  39. })();

Add your comment